sorting II

Complete

Succeeds: sorting

Summary

Sorting algorithms

Comparison based?In-place?Stable?
optimized bubble sortYYY
selection sortYYN
insertion sortYYY
merge sortYN, extra spaceY
quick sortYYdepends on partitioning strategy
counting sortNN, extra spacedepends on implementation
radix sortNN, extra spacedepends on per-digit sorting algorithm

Performance

  • with different input arrays
  • 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

Concept

Swap

  • exchange two elements
  • temporary storage uses only space regardless of how many swaps are done
java
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;
}

Minimum swaps to sort an array

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

In-place sorting

  • only require extra 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

Unsorted vs Sorted arrays

  • sorting makes the array easier to work with
UnsortedSorted
searchlinear search, binary search,
min/maxlinear search, first and last index,
kth smallest/largestlinear search,
quickselect,
k or (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

Search
array_search.png

sorting is not necessarily the best solution in all cases

Java blackbox sorting

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;