var arr = [4,2,1,5,6,9,11,10,32,22,13,24,2,54,11,10]; console.log(sort(arr, "min")) console.log(sort(arr, "max")) function sort(arr, type) { var arr_len = arr.length; for (var i = 0; i < arr_len; i++){ var left = 0; var right = i - 1; var temp = arr[i]; while (left <= right) { var middle = left + parseInt(right - left / 2); if (type.toLowerCase() == "min" ? arr[middle] > temp : arr[middle] < temp) { right = middle - 1; } else { left = middle + 1; } } for(var j = i - 1; j >= left; j--) { arr[j + 1] = arr[j]; } arr[left] = temp; } return arr; }