Counting how many times a specific value has appeared, etc. Shift every element in the array which is greater than the value of the selected element. Insertion Sort is a simple, easy to understand the algorithm that works best with a small data list by sorting each element in the data list one by one from left to right direction. # sort def insertion_sort(arr): for i in range(1, len(arr)): temp = arr[i] pos = binary_search(arr, temp, 0, i) + 1 for k in range(i, pos, -1): arr[k] = arr[k - 1] arr[pos] = temp def binary_search(arr, key, start, end): #key if end - start <= 1: if key < arr[start]: return start - 1 else: return start mid = (start + end)//2 if arr[mid] < key: return binary_search(arr, key, mid, end) elif arr[mid] > key: … You may also look at the following articles to learn more –, JavaScript Training Program (39 Courses, 23 Projects). Use binary insertion sort insert the current number, the index equals to how many numbers are smaller up to the current index (because it's sorted) var countSmallerBinarySearch = function(nums) { let sorted = [], result = []; for (let i=nums.length-1;i>=0;i--) { let left = 0, right = sorted.length; while(left < right) { let mid = left + Math.floor ( (right-left)/2); if (nums [i] > sorted [mid]) { left = mid + 1; } else { right = mid; } } … for (let i = 1; i < unsortedData.length; i++) {