sorting II


Succeeds: sorting

Summary

Comparison based

    • bubble sort
    • selection sort
    • insertion sort
    • merge sort
    • quick sort

Non-comparison based

    • counting sort
    • radix sort

Concept

In-place sorting

  • only require space
  • exclusively using swap

Stable sorting

  • relative order of elements with the same value is preserved
  • using < instead of <= when determining when a swap should occur

Performance

  • to sort in non-decreasing(ascending but allowing for duplicates) order
RandomSorted Non-decreasingSorted Non-increasingAlmost Sorted Non-decreasingAlmost Sorted Non-increasingMany Duplicates
Optimized Bubble Sort
Selection Sort
Insertion Sort
Merge Sort
Quick Sort
Randomized Quick Sort
Counting Sort

bubble and insertion sort are not entirely useless; if we know that the array will already be mostly sorted, they may be faster then merge/quick sort

Unsorted vs Sorted arrays

  • sorting makes the array easier to work with
ApplicationUnsortedSorted
searchlinear search, binary search,
min/maxlinear search, first and last index,
kth smallest/largestlinear search,
quickselect,
k and (last - k) index,
duplicatesnested loops, duplicates are adjacent,
counting repititonshash tableduplicates are adjacent,
set intersection/union (without repitition)nested linear search, nested binary search,
merge from merge sort,
two sumnested loops, two pointer approach,
count within rangehash tabletwo pointer approach,

Application

Swap

java
private static void swap(int a[], int i, int j) { // swap array elements i and j
	int temp = a[i]; // O(1) space
	a[i] = a[j];
	a[j] = temp;
}

Search
array_search.png

sorting is not necessarily the best solution in all cases

Leetcode: Shortest Unsorted Continuous Subarray

  • naive sort then check
java
int len = nums.length;
int[] sorted = Arrays.copyOf(nums, len);

Arrays.sort(sorted); // O(n log n)

int l = len, r = 0;

for (int i = 0; i < len; i++) { // O(n)
	if (nums[i] != sorted[i]) {
		l = Math.min(l, i);
		r = Math.max(r, i);
	}
}

return r - l >= 0 ? r - l + 1 : 0;

Minimum swaps to sort an array

  • each cycle of n elements takes n - 1 swaps
1352476