Basic Sorts
Bubble Sort
Bubble sort is a simple sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.
Code for bubble sort:
Selection Sort
Selection sort is a simple sorting algorithm that works by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.
Code for selection sort:
Insertion Sort
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.
In the worst case, the time complexity of the above algorithm is O(n^2). In the best case (for sorted or almost sorted lists), the time complexity of the above algorithm is O(n).
Quiz: Sorting
Bubble, Selection, and Insertion Sort all have O(n) time complexity: False. Each of these three sorting algorithms have a loop within a loop so they are O(n^2).
Bubble, Selection, and Insertion Sort have O(1) space complexity: True. All three of these sort the list in place. That means that they do not create additional copies of the list. That means it the space complexity is O(1).
Bubble, Selection, and Insertion Sort are all O(n) if you start with a sorted (or almost sorted) array: False. Only Insertion Sort is O(n) when you start with sorted (or almost sorted) data.
Last updated