if an array of size n has only 3 values 0 ,1 and 2 (repeated any number of times) what is the best way to sort them. best indicates complexity. consider space and time complexity both
To sort strings in an array based on length in JavaScript, call sort() method on this string array and pass a comparison function to sort() method, such that the comparison happens for the length of elements.
It essentially follows two steps: Divide the unsorted list into sub-lists until there are N sub-lists with one element in each ( N is the number of elements in the unsorted list). Merge the sub-lists two at a time to produce a sorted sub-list; repeat this until all the elements are included in a single list.
For arrays, array name arr indicates iterator pointing to first element of array and +n would increment that iterator by n elements. In your case, the sort algorithm should take beginning iterator and iterator pointing to one beyond last element.
Count the occurences of each number and afterward fill the array with the correct counts, this is O(n)
Sound's a lot like Dijkstra's Dutch National Flag Problem.
If you need a solution that doesn't use counting, check out http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/
Untested C-style solution:
int count[3] = {0, 0, 0};
for (int i = 0; i < n; ++i)
++count[array[i]];
int pos = 0;
for (int c = 0; c < 3; ++c)
for (int i = array[c]; i; --i)
array[pos++] = c;
Haskell two-liner:
count xs = Map.toList $ Map.fromListWith (+) [ (x, 1) | x <- xs ]
countingSort xs = concatMap ( \(x, n) -> replicate n x) (count xs)
> countingSort [2,0,2,1,2,2,1,0,2,1]
[0,0,1,1,1,2,2,2,2,2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With