import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Arrays; public class Search { /** * Make an array of random elements * @param N Size of the desired array * @return Array of size N of random elements from [0, N) */ public static int[] makeArray(int N) { int[] arr = new int[N]; for(int i = 0; i < N; ++i) { arr[i] = (int)(Math.random()*N); } return arr; } /** * Make a sorted array of random elements * @param N Size of the desired array * @return Sorted array of size N of random elements from [0, N) */ public static int[] makeSortedArray(int N) { int[] arr = new int[N]; for(int i = 0; i < N; ++i) { arr[i] = (int)(Math.random()*N); } Arrays.sort(arr); return arr; } /** * Linear search an array for a key * @param arr Array * @param key Key * @return true if arr contains key, false otherwise */ public static boolean linearSearch(int[] arr, int key) { for(int i = 0; i < arr.length; ++i) if(arr[i] == key) return true; return false; } /** * Binary search a sorted array for a key * @param arr Array * @param key Key * @return true if arr contains key, false otherwise */ public static boolean binarySearch(int[] arr, int key) { int low = 0; int high = arr.length - 1; while(low <= high) { int mid = (low + high)/2; if(key < arr[mid]) high = mid - 1; else if(key > arr[mid]) low = mid + 1; else /*key == arr[mid]*/ return true; } return false; } public static void main(String[] args) throws FileNotFoundException { PrintWriter pw = new PrintWriter("data_search.csv"); System.out.printf("%8s%15s%15s\n", "N", "Linear Search", "Binary Search"); pw.println("N,Linear Search,Binary Search"); int maxSize = 2000000; for(int N = 2; N < maxSize; N*=2) { //Determine repetitions for algorithm int repetitions = Math.max(10, maxSize/N); //Output N System.out.printf("%8d", N); pw.print(N); //Make an array int[] arr = makeArray(N); //Time linear search long startLS = System.nanoTime(); for(int k = 0; k < repetitions; ++k) { int key = (int)(Math.random() * N); linearSearch(arr, key); } long stopLS = System.nanoTime(); double durationLS = (stopLS - startLS)/1e9/repetitions; System.out.printf("%15.5e", durationLS); pw.print("," + durationLS); //Time binary search long startBS = System.nanoTime(); for(int k = 0; k < repetitions; ++k) { int key = (int)(Math.random() * N); binarySearch(arr, key); } long stopBS = System.nanoTime(); double durationBS = (stopBS - startBS)/1e9/repetitions; System.out.printf("%15.5e", durationBS); pw.print("," + durationBS); //Finish the line System.out.println(); pw.println(); } pw.flush(); pw.close(); } }