Sorting algorithms

Let's we have some collection of elements, for example array of integers.

5, 25, 36, 100, 75, 0, 23, 80, 90, 7

Our task is to sort this array to get the result

0, 5, 7, 23, 25, 36, 75, 80, 90, 100

If you need an algorithm implementation for objects and lists see full source Sort.java.

quick sort

In most cases this algorithm gives the best results.

The basic idea is to select any element within the range [ind1; indn], for example middle element M. Then move all elements that are greater than M to the right side, and all elements that are less than M to the left side.

  1. search first element that less (or equal) than M within range [M; indn]
  2. search first element that greater (or equal) than M within range [ind1; M]
  3. swap found elements
  4. continue from the first step until no more elements are found

After that, we repeat the algorithm recursively for two new ranges, the boundaries of which are [ind1; M] and [M; indn]

Time complexity is O(n*log(n)), in worst case O(n2).

Quick sort code

buble sort

This is most simple and lower algorithm. But in essence, quicksort is a modification of this method.

The basic idea is to swap two neighbor elements if they don't match the sorting conditions. Thus most greatest element will be at end (or begin) after first pass.

Time complexity is O(n2).

Bubble sort code

insertion sort

The basic idea here is to insert the next unsorted element into the desired position of an already sorted range.

  1. sort the first two elements
  2. take the third element and insert it in the right place
  3. apply step 2 to the fourth element and so on

Time complexity is O(n2), in best case O(n).

Isertion sort code

Shell sort

The main idea here is to use the insert method on a part of the collection being sorted. For example, on the first pass, process every sixteenth element. On the second pass, every eighth element. And only on the last pass, use the usual insertion sort.

In addition to the sequence shown (..., 16,8,4,2,1), other sequences can be used, for example, N/2, N/4, …, 1 where N length of collection.

Shell sort code

selection sort

In this algorithm, the main idea is to find the smallest or largest element in each pass and swap it with the first or last unsorted element depending on the sort condition.

other

There are other sorting methods, like pyromidal and merge