JMU
Searching
An Introduction with Examples


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Linear Search
Linear Search (cont.)
Binary Search
Binary Search (cont.)
Constant Time Search
Constant Time Search (cont.)

Setup

    /**
     * One Way to Setup for the Constant Time Search
     */
    int i;
    int a[n], indicator[m];

    .
    .
    .

    for (i=0; i < m; i++)
    {
	indicator[i] = 0;
    }


    for (i=0; i < n; i++)
    {
        indicator[a[i]] = 1;
    }
  

Search

return indicator[a[i]];
  
Constant Time Search (cont.)
Constant Time Search (cont.)

An Alternative Setup Algorithm

    /**
     * Another way to setup for the Constant Time Search
     */
    int i, j, prev;
    int a[n], indicator[m];

    .
    .
    .

    prev = 0;
    for (i=0; i < n; i++)
    {
        for (j=prev; j < a[i]; j++)
        {
	    indicator[j] = 0; // How many times is this done?
	}
        indicator[a[i]] = 1;

        prev = a[i] + 1;      // How many times is this done?
    }