Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting efficiently

I have an array of values which is almost, but not quite sorted, with a few values displaced (say, 50 in 100000). How to sort it most efficiently?

like image 657
algo-geeks Avatar asked Dec 15 '10 06:12

algo-geeks


People also ask

What is the efficiency of sorting?

Sorting algorithms are usually judged by their efficiency. In this case, efficiency refers to the algorithmic efficiency as the size of the input grows large and is generally based on the number of elements to sort. Most of the algorithms in use have an algorithmic efficiency of either O(n^2) or O(n*log(n)).

Which sorting technique is fast and efficient Why?

If you've observed, the time complexity of Quicksort is O(n logn) in the best and average case scenarios and O(n^2) in the worst case. But since it has the upper hand in the average cases for most inputs, Quicksort is generally considered the “fastest” sorting algorithm.

Which data structure is most efficient for sorting?

Quicksort is considered to be the fastest one among all the other sorting algorithms. The time complexity of Quicksort is O(n log n) in its best case, O(n log n) in its average case, and O(n^2) in its worst case.

What is the importance of sorting?

In sorting objects, they separate them according to similarities and differences. When comparing, the children determine if an object has more or less of an attribute. Classifying and sorting activities help children to develop a range of thinking skills and build the foundations for later problem-solving.


2 Answers

Under the assumption that the array is almost sorted, you could use one of the following :

Smoothsort

Wiki even has a java implementation on it. Since you can't do it faster than O(n) (since it takes that much time in order to even find out if an array is sorted or not) smoothsort is a good choice. More details here.

The advantage of smoothsort is that it comes closer to O(n) time if the input is already sorted to some degree

Coctail sort

The complexity of cocktail sort in big O notation is O(n2) for both the worst case and the average case, but it becomes closer to O(n) if the list is mostly ordered before applying the sorting algorithm,

Timsort

Java's arrays are actually now using timsort in java 7 in order to sort objects (sort()). Description of timsort here.

like image 100
Milan Avatar answered Oct 12 '22 03:10

Milan


Use insertion sort; it's great with almost-sorted arrays, since it's near O(n) time for them. I actually believe the .NET Framework uses insertion sort for sorting enum values internally (since they're often sorted), though I'd have to re-check that.

like image 34
user541686 Avatar answered Oct 12 '22 03:10

user541686