binarySearch Receives a generic one dimensional array and a generic key and

Binarysearch receives a generic one dimensional array

This preview shows page 3 - 6 out of 6 pages.

//**************************************************************************** //binarySearch: Receives a generic one-dimensional array and a generic key // and returns the location of the key (positive) or // a negative location if not found. //**************************************************************************** public <E extends Comparable<E>> int binarySearch(E[] list, E key) { int low = 0; int high = list.length - 1; return binarySearch (list, key, low, high); } public <E extends Comparable<E>> int binarySearch(E[] list, E key, int low, int high) { int mid; while(low <= high) { mid = (low + high) /2; if(list[mid].compareTo(key) == 0) // found, return mid return mid; else if(list[mid].compareTo(key) < 0) { low = mid + 1; } else { high = mid - 1; } } return -1; //when not found } //****************************************************************************
Image of page 3
//sort: Receives a generic arrayList and returns nothing. //**************************************************************************** public <E extends Comparable<E>> void sort(ArrayList<E> list) { //selection sort int minIdx ; for(int i = 0 ; i < list.size(); i++) { minIdx = i; for(int j = i + 1; j < list.size(); j++) { if(list.get(j).compareTo(list.get(minIdx)) < 0) minIdx = j; } if(minIdx != i) { E temp = list.get(i); list.set(i, list.get(minIdx)); list.set(minIdx, temp); } } } //**************************************************************************** //sort: Receives a generic one-dimensional array and returns nothing. //**************************************************************************** public <E extends Comparable<E>> void sort(E[] list) { //selection sort
Image of page 4
int minIdx ; for(int i = 0 ; i < list.length; i++) { minIdx = i; for(int j = i + 1; j < list.length; j++) { if(list[j].compareTo(list[minIdx]) < 0) minIdx = j; } if(minIdx != i) {
Image of page 5
Image of page 6

You've reached the end of your free preview.

Want to read all 6 pages?

  • Fall '08
  • STAFF
  • String Theory, Array, E max, public class Generics7, Misty Van Dyke

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture