fueanta

Bubble Sort + Binary Search

Oct 8th, 2016
159
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include "cstdio"
  2.  
  3. template< typename T >
  4. void interchange(T &x, T &y) {
  5.     x = x + y;
  6.     y = x - y;
  7.     x = x - y;
  8. }
  9.  
  10. void sort_asc(int arr[], int);
  11. int bi_search(int arr[], int, int);
  12.  
  13. int main() {
  14.     int sizeu; printf("Give Array Size: "); scanf("%d", &sizeu);
  15.     int arr[sizeu];
  16.     for (int i = 0; i < sizeu ; i++) {
  17.         printf("\nElement at index %d: ", i);
  18.         scanf("%d", &arr[i]);
  19.     }
  20.     printf("\nGiven Array: \n");
  21.     for (int i = 0; i < sizeu ; i++) {
  22.         printf("\nElement at index %d: %d", i, arr[i]);
  23.     }
  24.  
  25.     printf("\n\nAscending array elements....\n");
  26.     sort_asc(arr, sizeu);
  27.     for (int i = 0; i < sizeu ; i++) {
  28.         printf("\nElement at index %d: %d", i, arr[i]);
  29.     }
  30.  
  31.     printf("\n\nWhich element do you wish to search? : "); int item; scanf("%d", &item);
  32.     int position = bi_search(arr, sizeu, item);
  33.     if ( position != -1 )
  34.         printf("\nElement has found at index no %d.", position);
  35.     else
  36.         printf("\nElement could not be found.");
  37.     printf("\n");
  38.  
  39.     return 0;
  40. }
  41.  
  42. void sort_asc(int arr[], int n) {
  43.     for (int i = 0; i < n-1 ; i++) {
  44.         bool flag = false;
  45.         for (int j = 0; j < n-1 ; j++) {
  46.             if (arr[j] > arr[j+1]) {
  47.                 interchange(arr[j], arr[j+1]);
  48.                 flag = true;
  49.             }
  50.         }
  51.         if (flag == false)
  52.             break;
  53.     }
  54. }
  55.  
  56. int bi_search(int arr[], int n, int desired) {
  57.     int first = 0, last = n-1, position = -1;
  58.     bool found = false;
  59.     while (found != true && first <= last) {
  60.         int mid = (first+last)/2;
  61.         if (arr[mid] == desired) {
  62.             found = true;
  63.             position = mid;
  64.         }
  65.         else if (arr[mid] > desired)
  66.             last = mid - 1;
  67.         else
  68.             first = mid + 1;
  69.     }
  70.     return position;
  71. }
RAW Paste Data