home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tyc / list19_5.c < prev    next >
C/C++ Source or Header  |  1993-10-16  |  1KB  |  55 lines

  1.  /* Using qsort() and bsearch() with values.*/
  2.  
  3.  #include <stdio.h>
  4.  #include <stdlib.h>
  5.  
  6.  #define MAX 20
  7.  
  8.  int intcmp(const void *v1, const void *v2);
  9.  
  10.  main()
  11.  {
  12.      int arr[MAX], count, key, *ptr;
  13.  
  14.      /* Enter some integers from the user. */
  15.  
  16.      printf("Enter %d integer values; press Enter after each.\n", MAX);
  17.  
  18.      for (count = 0; count < MAX; count++)
  19.          scanf("%d", &arr[count]);
  20.  
  21.      puts("Press a key to sort the values.");
  22.      getch();
  23.  
  24.      /* Sort the array into ascending order. */
  25.  
  26.      qsort(arr, MAX, sizeof(arr[0]), intcmp);
  27.  
  28.      /* Display the sorted array. */
  29.  
  30.      for (count = 0; count < MAX; count++)
  31.          printf("\narr[%d] = %d.", count, arr[count]);
  32.  
  33.      puts("\nPress a key to continue.");
  34.      getch();
  35.  
  36.      /* Enter a search key. */
  37.  
  38.      printf("Enter a value to search for: ");
  39.      scanf("%d", &key);
  40.  
  41.      /* Perform the search. */
  42.  
  43.      ptr = (int *)bsearch(&key, arr, MAX, sizeof(arr[0]),intcmp);
  44.  
  45.      if ( ptr != NULL )
  46.          printf("%d found at arr[%d].", key, (ptr - arr));
  47.      else
  48.          printf("%d not found.", key);
  49.  }
  50.  
  51.  int intcmp(const void *v1, const void *v2)
  52.  {
  53.      return (*(int *)v1 - *(int *)v2);
  54.  }
  55.