Bubble Sort
The bubble sort makes multiple passes through a list. It compares adjacent items and exchanges those that are out of order. Each pass through the list places the next largest value in its proper place. In essence, each item “bubbles” up to the location where it belongs.
1 | def BubbleSort(list): |
([8, 15, 17, 20, 26, 31, 31, 44, 54, 55, 63, 77, 93], 78, 43)
Selection Sort
The selection sort improves on the bubble sort by making only one exchange for every pass through the list. In order to do this, a selection sort looks for the largest value as it makes a pass and, after completing the pass, places it in the proper location. As with a bubble sort, after the first pass, the largest item is in the correct place. After the second pass, the next largest is in place. This process continues and requires n−1 passes to sort n items, since the final item must be in place after the (n−1) st pass.
1 | def SelectionSort(list): |
([8, 15, 17, 20, 26, 31, 31, 44, 54, 55, 63, 77, 93], 78, 12)
Insertion Sort
The insertion sort, although still O(n2), works in a slightly different way. It always maintains a sorted sublist in the lower positions of the list. Each new item is then “inserted” back into the previous sublist such that the sorted sublist is one item larger
1 | def InsertionSort(list): |
([8, 15, 17, 20, 26, 31, 31, 44, 54, 55, 63, 77, 93], 44, 44)
Shell Sort
The shell sort, sometimes called the “diminishing increment sort,” improves on the insertion sort by breaking the original list into a number of smaller sublists, each of which is sorted using an insertion sort. The unique way that these sublists are chosen is the key to the shell sort. Instead of breaking the list into sublists of contiguous items, the shell sort uses an increment i, sometimes called the gap, to create a sublist by choosing all items that are i items apart.
1 | def gapinsertionsort(nums,start,gap): |
4 [20, 26, 15, 8, 54, 31, 44, 17, 63, 31, 93, 55, 77]
1 [8, 15, 17, 20, 26, 31, 31, 44, 54, 55, 63, 77, 93]
[8, 15, 17, 20, 26, 31, 31, 44, 54, 55, 63, 77, 93]
Merge Sort
Merge sort is a recursive algorithm that continually splits a list in half. If the list is empty or has one item, it is sorted by definition (the base case). If the list has more than one item, we split the list and recursively invoke a merge sort on both halves. Once the two halves are sorted, the fundamental operation, called a merge, is performed. Merging is the process of taking two smaller sorted lists and combining them together into a single, sorted, new list.
1 | def MergeSort(list): |
[8, 15, 17, 20, 26, 31, 31, 44, 54, 55, 63, 77, 93]
Reference
Problem Solving with Algorithms and Data Structures Using Python. Bradley N. Miller, David L. Ranum. 2005