Sorting

Top K problem

Optimization progress:

https://leetcode.com/problems/k-closest-points-to-origin/discuss/220235/Java-Three-solutions-to-this-classical-K-th-problem.

Randomization

Shuffle

Fisher–Yates shuffle:

private void shuffle(int nums[]) {
    final Random random = new Random();
    for (int i = nums.length - 1; i >= 0; i--) {
    	int j = random.nextInt(i+1);
    	exchange(nums, j, i);
    }
}

Reservoir sampling

Explain: https://www.youtube.com/watch?v=A1iwzSew5QY

Sorting in linkedlist

merge sort: https://leetcode.com/problems/sort-list

selection sort: https://leetcode.com/problems/insertion-sort-list/description/

Summary

Merge Sort

Quick Sort

Bubble Sort

Selection Sort

Insertion Sort

Heap Sort

https://www.geeksforgeeks.org/heap-sort/

  • Array represent a heap (Complete Binary Tree) : root i, left 2i+1, right 2i+2;

  • heapify the heap, make it maxHeap

  • swap root and last one, therefore 'remove' largest to the array tail

  • heapify the rest

Shell Sort

Bucket Sort

https://leetcode.com/problems/top-k-frequent-elements/description/ https://leetcode.com/problems/top-k-frequent-words/description/

special sorting

Reference

https://www.toptal.com/developers/sorting-algorithms

Last updated

Was this helpful?