Sorting
Last updated
Last updated
Selection sort is a simple algorithm, but inefficient.
First, find the smallest element using a linear scan and move it to the front (swap). Then, find the second smallest and move it, again doing a linear scan. Continue doing this until all the elements are in place.
Time Complexity: | Space Complexity: |
In this algorithm, we start at the beginning of the array and swap the first two elements if the first is greater than the second. Then, we go to the next pair, and so on, continuously making sweeps of the array until it is sorted.
Time Complexity: | Space Complexity: |
Time Complexity: | Space Complexity: ? |
Quicksort is another sorting algorithm based on the Divide and Conquer programming technique. In this algorithm, an element is first chosen as the pivot, and the entire array is then partitioned around this pivot.
As you've probably guessed, a good pivot is crucial for an efficient sort. The pivot can either be a random element, the media element, the first element, or even the last element.
Implementations of quicksort often differ in the way they choose a pivot. In the average case, quicksort will sort a large array with a good pivot in just O(nlogn) time.
The general pseudocode of quicksort repeatedly partitions the array on the pivot and positions it in the correct position of the subarray. It also places the elements smaller than the pivot to its left and elements greater than the pivot to its right.
Time Complexity:
| Space Complexity:
|
Divide and Conquer Programming Technique
Merge sort divides the array in half, sorts each of those halves, and then merge them back together.
Each of those halves has the same sorting algorithm applied to it.
Time Complexity: | Space Complexity: |
The space complexity being O(n)
is due to the auxiliary space used to merge the parts of the array.