10b: Applets; Searching & Sorting

ICS211, Spring 2013
Dr. Zach

(switch view)

Status

Last time

Applets

Applets extend JApplet

public class NumberPad extends JApplet implements ActionListener {

Create an HTML page

Test it locally

When it doesn't work

Upload

When it doesn't work

Searching

Searching

Linear search code

Linear search

Binary search

public int indexOf(E item) {
  return binarySearch(this.array, item, 0, array.length - 1);
}

public static <E extends Comparable<E>> int binarySearch(E[] data, 
                                                 E value, int start, int end) {
  if(start > end) {
    return -1;  //not found
  }
  int middle = (start + end) / 2;
  if(data[middle].compareTo(value) == 0) {
    return middle;  //found it!  Return its index
  }
  if(data[middle].compareTo(value) < 0) {
    return binarySearch(data, value, middle + 1, end);
  } else {
    return binarySearch(data, value, start, middle - 1);
  }
}

Binary search code

public int indexOf(E item) {
  int low = 0;
  int high = array.length - 1;
  while (low <= high) {
    int mid = (low + high) / 2;
    if (item.compareTo(array[mid]) == 0) {
      return mid;
    }else if (item.compareTo(array[mid]) < 0) {
      high = mid - 1;
    } else {
      low = mid + 1;
    }
  }
  return -1;  //not found
}

Searching conclusion

Sorting

Insertion and Selection sort

SortedList approach

Insertion sort

Insertion sort code

//from wikipedia pseudocode
for (int i = 1; i < array.length; i++) {
  E item = array[i];
  int hole = i;
  while (hole > 0 && array[hole - 1].compareTo(item) > 0) {
    array[hole] = array[hole - 1];
    hole--;
  }
  array[hole] = item;
}

Stable sorts

Selection sort

Selection sort code

//from wikipedia code
for (int i = 0; i < array.length - 1; i++) {
  int min = i;  //maybe current item is min...
  //find smaller than min
  for (int seek = i + 1; seek < array.length; seek++) {
    if (array[seek].compareTo(array[min]) < 0) {
      min = seek;
    }
  }
  //swap min
  if (min != i) {  //optional check to reduce writes
    E temp = array[i];
    array[i] = array[min];
    array[min] = temp;
  }
}

Insertion vs Selection

Summary

For next time...