CPSC 331: Tutorial 3

In Class Exercise

PhD Student

Spring 2018

Today

In class, you performed a complexity analysis of binary search.

 

You are now asked to conduct experiments that will validate your analysis for the average case.

 

In this tutorial, you will investigate the time complexity of binary search empirically by counting the number of comparisons it takes to search for an integer in a sorted array.

Code

int binarySearch(int[] arr, int key) {
   int lo = 0, mid, hi = arr.length-1;
   while (lo <= hi) {
      mid = (lo + hi) / 2;
      if (key < arr[mid])
         hi = mid - 1;
      else if (arr[mid] < key)
         lo = mid + 1;
      else return mid;   // success
   }
   return -1;   // key not found
}

Use your code to perform a number of experiments on arrays of different sizes \(N=2^k\),  \(k=5,\cdots,30\). For each input size, determine the average number of comparisons for all searches in the range 0 to N.

When \(k\) is Large

For large input sizes, you may run out of memory. You can increase the amount of heap space available to the JVM by using the -Xmx option when launching your program. For example, if your main program resides in the class Experiment, launch the JVM as follows:

java -Xmx8g Experiment

This will set the max heap size to 8GB. This also requires a 64-bit JVM which most modern JVMs should be. To be sure, you can use the additional option -d64 when launching your program. You are also limited by the memory available on the machine. Try and collect data for the maximum possible \(k\).   

Graph the Trend

Generate a plot of the average number of comparisons vs k. What sort of a trend do you expect?

 

Verify that you results are consistent with the analysis you did in class. 

I'll show you how to use Excel (or whatever LibreOffice equivalent we have in the lab) to do this.

Next Day

Recursion and Sorting

CPSC 331: Tutorial 3

By Joshua Horacsek

CPSC 331: Tutorial 3

  • 1,061