Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort repeating numbers

Tags:

c

sorting

 int a[] = {0, 0, 0, 0, 0, 0, 1, 1, 2, 0, 0, 2, 1, 1, 0, 0, 0, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0};

What is the best approach to sort such series? Keep in mind I want the minimum complexity.

like image 809
user2620215 Avatar asked Nov 18 '25 13:11

user2620215


1 Answers

If the numbers have a small upper limit, you can use a counting sort: count how many times each item appears in the array, then walk through the array, and put in as many items as you counted for each of the values.

For example, in your case you would count 17 zeros, 7 ones, and 4 twos. Set the first 17 items to 0, the following 7 to 1, and the remaining 4 to 2 to get a sorted array.

This approach has linear complexity.

like image 187
Sergey Kalinichenko Avatar answered Nov 21 '25 04:11

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!