Download code

Jump to: navigation, search

Back to Binary_search_(C)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

binary_search.c

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Binary_search_(C)?oldid=16429
14 */
15 
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <time.h>
19 
20 int binary_search(int a[], int low, int high, int target) {
21     while (low <= high) {
22         int middle = low + (high - low)/2;
23         if (target < a[middle])
24             high = middle - 1;
25         else if (target > a[middle])
26             low = middle + 1;
27         else
28             return middle;
29     }
30     return -1;
31 }
32 
33 /* For qsort */
34 int less_int(const void* left, const void* right) {
35     return *((const int*)left) - *((const int*)right);
36 }
37 
38 int main(int argc, char* argv[]) {
39     clock_t start;
40     int num_elements = atoi(argv[1]);
41     int* a = (int*)malloc(num_elements*sizeof(int));
42     int i;
43     for(i=0; i<num_elements; i++) {
44         do {
45             a[i] = rand() % num_elements;
46         } while(a[i] == num_elements/7);
47     }
48     qsort(a, num_elements, sizeof(int), less_int);
49 
50     start = clock();
51     for(i=0; i<50000; i++) {
52         int present_val = a[rand() % num_elements];
53         int found_at = binary_search(a, 0, num_elements - 1, present_val);
54         if (found_at == -1 || a[found_at] != present_val)
55             puts("ERROR");
56     }
57     printf("Average search time: %f sec\n",
58            ((double)(clock() - start))/(CLOCKS_PER_SEC)/50000);
59 
60     if (binary_search(a, 0, num_elements - 1, num_elements/7)   != -1 ||
61         binary_search(a, 0, num_elements - 1, -1)               != -1 ||
62         binary_search(a, 0, num_elements - 1, num_elements + 1) != -1)
63     {
64         puts("ERROR");
65     }
66     return 0;
67 }


hijacker
hijacker
hijacker
hijacker