各种sorting总结

来源:互联网 发布:win7 mac地址修改 编辑:程序博客网 时间:2024/06/05 09:32

Selection sort:

1. Divide the input into two part: sublist of items already sorted and sublist of items to be sorted.
2. Find the smallest element in unsorted sublist, exchange it with the leftmost unsorted element.
3. Moving the sublist boundary one element to the right.
Example:  64 25 12 22 11 -> 11 64 25 12 22 -> 11 12 64 25 22 -> 11 12 22 64 25-> 11 12 22 25 64
Performance: worst O(n2), best O(n2), average O(n2), worst space O(n), O(1) auxiliary

Insertion sort:
for i ← 1 to length(A)
    j ← i
    while j > 0 and A[j-1] > A[j]
        swap A[j] and A[j-1]
        j ← j - 1
Performance: worst O(n2), best O(n), average O(n2), worst space O(n), O(1) auxiliary

Shell sort:
The method starts by sorting elements far apart from each other and progressively reducing the gap between them.
# Sort an array a[0...n-1].
gaps = [701, 301, 132, 57, 23, 10, 4, 1]
foreach (gap in gaps)
{
    # Do an insertion sort for each gap size.
    for (i = gap; i < n; i += 1)
    {
        temp = a[i]
        for (j = i; j >= gap and a[j - gap] > temp; j -= gap)
        {
            a[j] = a[j - gap]
        }
        a[j] = temp
    }
}
Example: The first pass, 5-sorting, performs insertion sort on separate subarrays (a1, a6, a11), (a2, a7, a12), (a3, a8), (a4, a9), (a5, a10). For instance, it changes the subarray (a1, a6, a11) from (62, 17, 25) to (17, 25, 62). The next pass, 3-sorting, performs insertion sort on the subarrays (a1, a4, a7, a10), (a2, a5, a8, a11), (a3, a6, a9, a12). The last pass, 1-sorting, is an ordinary insertion sort of the entire array (a1,..., a12).
Performance: depends on gap sequence, worst space O(n), O(1) auxiliary

Bubble sort:
It works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
Performance: worst O(n2), best O(n), average O(n2), worst space O(1) auxiliary

Mergesort:
1. Divide array into two halves.
2. Recursively sort each half.
3. Merge two halves.
Performance: worst O(nlogn), best O(nlogn), average O(nlogn), worst space O(n) auxiliary

Quicksort:
0. Random shuffle to guarantee against worst case.
1. Pick a pivot element.
2. Reorder the list so that elements less than pivot come before the pivot, greater than pivot come after pivot.
3. Recursively apply above steps to two sublists.
Performance: worst O(n2), best O(nlogn), average O(nlogn), worst space O(n) auxiliary

Heapsort:
1. Build a heap out of the data.
2. A sorted array is created by repeatedly removing the largest element from heap, and inserting it into the array.
3. Reconstruct heap.
Performance: worst O(n2), best O(nlogn), average O(nlogn), worst space O(1) auxiliary

0 0