Elementary Sorting: For I in (0 ,... N) : Findindexofminimum Swap (I, I - Min)
Elementary Sorting: For I in (0 ,... N) : Findindexofminimum Swap (I, I - Min)
1
1
Selection Sort
for i in [0 ,... n ) :
find index of minimum
swap (i , i_min )
2
2
1
Insertion Sort
for i in [1 ,... n ) :
j = i
while ( a [j -1] > a [ j ]) :
swap (j , --j )
Shellsort
Idea: insertion sort that moves entries more than one position at a time by
h-sorting the array. An h-sorted array is h interleaved, sorted subsequences
- every pair separated by a distance of h is sorted.
Shellsort h-sorts an array for a decreasing sequence of values h. Use
insertion sort because large increments at the beginning means small subarrays, and when the increment grows smaller, the array is very nearly sorted.
The mathematical fact that makes shellsort possible is that a g-sorted array
is still g-sorted after being h-sorted.
Knuth recommends using the sequence xn = 3xn1 +1 for shellsort sizes,
and Sedgewick recommends a merge of (94!)(92i )+1 and 4i (32i )+1
that goes 1, 5, 19, 41, 109, 209, 505, 929, 2161, 3905 . . ..
The worst-case number of comparisons using the 3x+1 model is O(n3/2 ),
and nobody has determined an accurate model for the average-case running
time of the algorithm yet.
Elementary Sorting
4
Applications of Sorting
4.1
Shuffling
Shuffle sort: generate a random real number for each array entry, then sort.
Provided no duplicate values, this randomly permutes the array. However,
this is lower-bounded by O(n log n) due to the limit on comparison-based
sorting.
The Knuth shuffle is an algorithm that shuffles an array to a uniformly
random permutation in linear time.
2
for i in [0 ,... n ) :
swap (i , rand (0 , i ) )
4.2
Convex Hull