DS
DS
Advantages:
Simple implementation
Efficient for (quite) small data sets
Adaptive (i.e., efficient) for data sets that are already substantially
sorted: the time complexity is O(n + d), where d is the number of
inversions
More efficient in practice than most other simple quadratic (i.e.,
O(n2)) algorithms such as selection sort or bubble sort; the best case
(nearly sorted input) is O(n)
Stable ; i.e., does not change the relative order of elements with equal
keys
In-place ; i.e., only requires a constant amount O(1) of additional
memory space
Online ; i.e., can sort a list as it receives it
Insertion Sort Algorithm
Now we have a bigger picture of how this sorting technique
works, so we can derive simple steps by which we can achieve insertion
sort.
Step 4 − Shift all the elements in the sorted sub-list that is greater than
the value to be sorted
All elements smaller than the pivot are moved before it and all
greater elements are moved after it. This can be done efficiently in
linear
time and in-place.
2. Reorder the list so that all elements with values less than the pivot
come before the pivot, while all elements with values greater than the
pivot come after it (equal values can go either way).
After this partitioning, the pivot is in its final position. This is called the
partition operation.
function quicksort(array)
var list less, greater
if length(array) ≤ 1
return array // an array of zero or one elements is already sorted
select and remove a pivot value pivot from array
for each x in array
if x ≤ pivot then append x to less
else append x to greater
return concatenate(quicksort(less), pivot, quicksort(greater)