Quick Sort (Randomized)
Quicksort is a Divide and Conquer algorithm. Like all divide-and-conquer algorithms, it first divides a large array into two smaller subarrays and then recursively sort the subarrays. Basically, three steps are involved in the whole process:
- Pivot Selection
Randomly (otherwise it will time out) pick an element, called pivot, from the array.
- Partitioning
Reorder the array such that all elements with values less than the pivot come before the pivot. In contrast, all elements with values greater than the pivot come after it. The equal values can go either way. After this partitioning, the pivot is in its final position.
- Recursion
Recursively apply the Step 1 & 2 to each subarray.
Code
1 | // Quick Sort |
Heap Sort
A heap is a complete binary tree. An ordered balanced binary tree is called a Min-heap, where the value at the root of any subtree is less than or equal to the value of either of its children. An ordered balanced binary tree is called a Max-heap, where the value at the root of any subtree is more than or equal to the value of either of its children.
To sort any list into a logical order following steps are followed :
- Convert the list into heap.
- Convert this heap into max heap.
- Replace the root with the last item of the heap.
- Delete this node and reduce the size of the heap by 1.
- Repeat Step 1-4 until sorted.
Code
1 | // Heap Sort |
Bucket Sort
- Calculate the number of each element in nums. Use count to store these numbers.
- Traverse count. i-th element’s value is the occurrence times of the corresponding number.
Code
1 | vector<int> bucketSort(vector<int>& nums) { |
Merge Sort
Merge sort is a divide and conquer algorithm:
- If it is only one element in the list it is already sorted, return.
- Divide the list recursively into two halves until it can no more be divided.
- Merge the smaller lists into new list in sorted order.
Ket function: merge(nums, start, end, mid)
The essence of this function is to merge 2 sorted arrays. Pointer i and j respectively point to the first position of the first half and the second half of the array nums. Then compare nums[i] and nums[j]. If nums[i] > nums[j], push nums[i] to the temporary array tmp, and i++, otherwise push nums[j] to the temporary array tmp, and j++. When one part is done, push the rest of the other part to the tmp. Finally, cover unsorted array nums by sorted tmp.
Code
1 | class Solution { |