Chapter 13: Searching and Sorting
Big Oh
A notation for describing run-time that means the run-time is no worse than a given function.
merge sort
recursively divide the array in half and sort it
quick sort
recursively partition array based on a middle value
bogo sort
shuffle and pray
radix sort
sort integers by last digit, then second to last, and so on
bubble sort
swap adjacent pairs that are out of order
natural ordering
Rules governing the relative placement of all values of a given type.
Runtime of three statements
3
Runtime of a for loop for(int i = 1; i<=n; i++}{ statement1; statement2; statement3; }
3n
Runtime of nested for loop for(int i = 1; i<=n; i++}{ for(int j = 1; j<=n; j++}{ statement1; statement2; statement3; } }
3n^2
comparison based sorting
Determining order by comparing pairs of elements
Binary Search runtime
O(log n)
Bubblesort runtime
O(n^2)
InsertionSort
O(n^2)
SelectionSort runtime
O(n^2)
complexity class
a category of algorithm efficiency based on the algorithm's relationship to the input size N
efficiency
a measure of the use of computing resources by code, can be relative to speed/memory, a.k.a. runtime
insertion sort
build an increasingly large sorted front portion
growth rate
change in runtime as input data size (n) changes
bucket sort
cluster elements into smaller groups, sort them
comparison function
code that, when given two values of a given type, decides their relative ordering
binary search
locates a target value in a sorted array/list by successively eliminating half of the array from consideration
sequential search
locates a target value in an array/list by examining each element from start to finish
selection sort
look for the smallest element, move to front
heap sort
place the values into a sorted tree structure
Binary Search Algorithm
public static int binarySearch( int[] a, int target ){ int min=0; int max=a.length-1; while (min<=max){ int min = (min+max)/2; if (a[mid]<target){ min = mid+1; } else if (a[mid]>target){ max=mid-1; } else { return mid; //target found } } return -(min+1); //target not found }
bogoSort
public static void _________ (int[] a){ while(!isSorted(a)){ shuffle(a); } } public static boolean isSorted(int[] a){ for(int i=0; i<a.length-1;i++){ if(a[i]>a[i+1]){ return false; } return true; } public static shuffle (int[] a){ for( int i=0; i< a.length - 1; i++){ int range = a.length-1-(i+1)+1; int j=(int) (Math.random()*range+(i+1)); swap (a, i, j); } } public static void swap(int[] a, int i, int j){ if (i!=j){ int temp= a[i]; a[i] = a[j]; a[j] = temp; } }
SelectionSort
public static void ______________(int[] a){ for(int i=0; i<a.length-1;i++){ int min = i; for (int j=i+1; j<a.length; j++){ if(a[j]<a[min]){ min=j; } } swap(a, i, min); } } public static void swap(int[] a, int i, int j){ if (i!=j){ int temp= a[i]; a[i] = a[j]; a[j] = temp; } }
sorting
rearranging the values in an array or collection into a specific order (usually into their natural ordering)