10a: Applets; Searching & Sorting

ICS211, Fall 2012
Dr. Zach

(switch view)

Status check

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

//assuming array-based implementation
public int indexOf(E item) {
  for (int i = 0; i < this.array.length; i++) { 
    E element = this.array[i];
    if (element.equals(item)) {
      return i;
    }
  }
  return -1;  //not found
}

Linear search

Binary search

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

Sort as you insert

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;
}

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

For next time...