Lesson 4: What are Sorting Algorithms?
Selection Sort
Selection Sort divides the data into two parts: sorted and unsorted. On each iteration, the Selection Sort finds the minimum entry from the unsorted part and places this given entry at the end of the sorted part.
Example: Consider the unsorted array [7,4,2,9,8,1]. If you wish to sort this array in ascending order, the Selection Sort algorithm behaves as follows:
Array = [7,4,2,9,8,1] for m in range(len(Array)): minimum = m for n in range(m + 1, len((Arrau)): if Array[minimum] > Array[n]: minimum = n Array[m], Array[minimum] = Array[minimum], Array[m] print("Sorted array") for m in range(len(Array)): print("%d" %Array[m])
Sorted array 1 2 4 7 8 9
Insertion Sort
Similarly, Insertion Sort also divides a given problem into sorted and unsorted parts. For each element in the unsorted part, the algorithm places it in the correct position of the sorted part. On each iteration, the Insertion Sort compares the current element with the preceding element. If the element is less than the preceding element, it compares it to all the elements before.
Example: Lets take the array we used in the Selection Sort example and sort it using Insertion Sort. The code looks like this:
Array[7,4,2,9,8,1] for m in range(1, len(Array)): key = Array[m] n = m -1 while n >= 0 and key < Array[n]: Array[n + 1] = Array[n] n -= 1 Array[n + 1] = key print("Sorted array") for m in range(len(Array)): print("%d" % Array[m]
Sorted array 1 2 4 7 8 9
Try it!
Click "SORT" to see how Insertion Sorting Algorithms work in real life:
You can also "ADD MORE ITEMS" or "CLEAR" all items if you wish.
Insertion Sort Animation