bigArray.close();
}
static void binarySearch() throws IOException {
IBigArray bigArray = new BigArrayImpl(MergeSortHelper.SAMPLE_DIR, "sample_array");
// randomly get some items which can be found later
int searchLoopLimit = 10000;
List<String> randomKeys = new ArrayList<String>();
Random random = new Random();
for(int i = 0; i < searchLoopLimit / 2; i++) {
long randomIndex = (long)(random.nextDouble() * maxNumOfItems);
String randomKey = new String(bigArray.get(randomIndex));
randomKeys.add(randomKey);
}
bigArray.close(); // close to release cache, otherwise the performance of binary search will not be real.
bigArray = new BigArrayImpl(MergeSortHelper.SAMPLE_DIR, "sample_array");
MergeSortHelper.output("Single thread binary search begin ...");
int foundCount = 0;
long start = System.currentTimeMillis();
for(int i = 0; i < searchLoopLimit; i++) {
String randomKey = null;
if (i < searchLoopLimit / 2) {
randomKey = randomKeys.get(i);
} else {
randomKey = MergeSortHelper.genRandomString(itemSize);
}
long result = BinarySearchHelper.binarySearch(bigArray, randomKey, 0, bigArray.size() - 1);
if (result != BinarySearchHelper.NOT_FOUND) {
foundCount++;
}
}
long end = System.currentTimeMillis();
MergeSortHelper.output("Binary search finished.");
MergeSortHelper.output("Time to search " + searchLoopLimit + " items in the big array is " + (end - start) + " ms.");
MergeSortHelper.output("Average search time is " + (double)(end - start) / searchLoopLimit + "ms.");
MergeSortHelper.output("Found count is " + foundCount);
// have done with the big array, empty it and delete back data files to save disk space
bigArray.removeAll();
bigArray.close();
}