Searching Slowly And Fastly
public static int find(int x, int[] a, int n) { for (int loc = 0; loc < n; loc++) if (a[loc] == x) return loc;//found return -1;//not found } iterative search
binarySearch public static int binarySearch(int x, int[] sorted, int n) { int low = 0; //inclusive int end = n; //exclusive while (low < end) { //find which half of remaining array holds x int mid = (low + end) /2; //integer division if (x == sorted[mid]) return mid;//found if (x > sorted[mid]) low = mid+1; //inclusive else end = mid; //exclusive } return -1; //not found
Sorting Slowly
insert public static void insert(int x, int[] sorted, int n) { while (n > 0 && x < sorted[n-1]) {//shift until find insertion point sorted [n] = sorted[n-1]; } sorted [n] = x; }
insertionSort public static void insertionSort(int[] a, int[] sorted, int n) { for (int k = 0; k < n; k++) { //repeated insert insert(a[k], sorted, k); } }
insertionSort public static void insertionSort(int[] a, int n) { for (int k = 0; k < n; k++) {//repeatedly insert in place insert(a [k], a, k); } }
swap public static void swap(int[] array, int a, int b ) { //save a int temp = array[a]; //copy b to a array[a] = array[b]; //copy a to b array[b] = temp; }
findMax public static int findMax(int[] array, int n) { int locMax = 0; for (int k = 1; k array[locMax]) locMax = k; //index of largest element return locMax; }
selectSort public static void selectSort (int[] array, int n) { for (int k = n; k > 1; k--) { //repeat until sorted //find largest unsorted value value int select = findMax(array, k); //move to end swap(array, select, k-1); } }