Sorts
Sorts
Insetion Sort
The insertion sort algorithm iterates through an input array and removes one element per iteration, finds the place the element belongs in the array, and then places it there. This process grows a sorted list from left to right. The algorithm is as follows:
To sort an array of size n in ascending order:
Iterate from arr[1] to arr[n] over the array.
Compare the current element (key) to its predecessor.
If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.
The key is that: arr[i - 1] is always sorted.
Implementation
1 | def insertion_sort(lst): |
Merge Sort
Mergesort has two steps: merging and sorting. The algorithm uses a divide-and-conquer approach to merge and sort a list.
Divide and conquer is a technique used for breaking algorithms down into subproblems, solving the subproblems, and then combining the results back together to solve the original problem. It can be helpful to think of this method as divide, conquer, and combine.
The mergesort algorithm focuses on how to merge together two pre-sorted arrays such that the resulting array is also sorted. Mergesort can be implemented either recursively or iteratively.
Here is the recursive mergesort algorithm:
- If the list has only one element, return the list and terminate. (Base case)
- Split the list into two halves that are as equal in length as possible. (Divide)
- Using recursion, sort both lists using mergesort. (Conquer)
- Merge the two sorted lists and return the result. (Combine)
The merge step:
- Create an empty list called the result list.
- Do the following until one of the input lists is empty: Remove the first element of the list that has a lesser first element and append it to the result list.
- When one of the lists is empty, append all elements of the other list to the result.
1 | def merge_sort(lst): |