// This class shows some array applications, including // findMax, findMin, sort, search // For classroom discussion. // Xiannong Meng // April 1998 public class ArrayApps { private int[] data; public ArrayApps(int[] source) { data = new int[source.length]; for (int i = 0; i < source.length; i ++) data[i] = source[i]; } public int findMaxIndex() // return the index of max { int index; if (data.length == 0) return -1; else { int tempMax = data[0]; index = 0; for (int i = 0; i < data.length; i ++) if (tempMax < data[i]) { tempMax = data[i]; index = i; } } // else return index; } // end of findMaxIndex public int findMinIndex() // return the index of min { int index; if (data.length == 0) return -1; else { int tempMin = data[0]; index = 0; for (int i = 0; i < data.length; i ++) if (tempMin > data[i]) { tempMin = data[i]; index = i; } } // else return index; } // end of findMinIndex public int search(int key) // return the index of the location holding 'key' { for (int i = 0; i < data.length; i ++) if (data[i] == key) return i; return -1; // not found } public int binSearch(int key) // binary search, return the index of the location where 'key' is { int low, hi, mid; low = 0; hi = data.length; while (low <= hi) { mid = (low + hi) / 2; if (key == data[mid]) // found the key return mid; else if (key > data[mid]) // search for the higher half low = mid + 1; else // search for lower half hi = mid - 1; } // end of while. return -1; // not found } public void sort() // a simple selection sort is used { int min, minIndex; for (int i = 0; i < data.length; i ++) { min = data[i]; // this is a temporary min minIndex = i; for (int j = i + 1; j < data.length; j ++) if (data[j] < min) { min = data[j]; // update the min minIndex = j; } // end for j and if if (minIndex != i) // a new min is found in this round { data[minIndex] = data[i]; data[i] = min; } } // end for i } // end sort public void print() { for (int i = 0; i < data.length; i ++) System.out.println(data[i]); } // end print }