Java Reference
In-Depth Information
public static int search(String key, Index[] list, int n) {
//searches list[1..n] for key. If found, it returns the location; otherwise
//it returns the negative of the location in which key should be inserted.
int lo = 1, hi = n;
while (lo <= hi) { // as long as more elements remain to consider
int mid = (lo + hi) / 2;
int cmp = key.compareToIgnoreCase(list[mid].partNum);
if (cmp == 0) return mid; // search succeeds
if (cmp < 0) hi = mid - 1; // key is 'less than' list[mid].partNum
else lo = mid + 1; // key is 'greater than' list[mid].partNum
}
return -lo; // key not found; insert in location lo
} // end search
public static void printIndex(Index[] index) {
System.out.printf("\nThe index is as follows: \n\n");
int numRecords = index[0].recNum;
for (int h = 1; h <= numRecords; h++)
System.out.printf("%s %2d\n", index[h].partNum, index[h].recNum);
} //end printIndex
} //end class CreateIndex
class Part {
String partNum, name;
int amtInStock;
double price;
public Part(String pn, String n, int a, double p) {
partNum = pn;
name = n;
amtInStock = a;
price = p;
}
public void printPart() {
System.out.printf("Part number: %s\n", partNum);
System.out.printf("Part name: %s\n", name);
System.out.printf("Amount in stock: %d\n", amtInStock);
System.out.printf("Price: $%3.2f\n", price);
}
} //end class Part
class Index {
String partNum;
int recNum;
public Index(String p, int r) {
partNum = p;
recNum = r;
}
} //end class Index
Search WWH ::




Custom Search