avr39-ripe

sortInsert + binSearch

Jul 9th, 2019
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3.  
  4. //Binary search of user entered array
  5. //Useful code of binary search is at the end of file!
  6.  
  7. using namespace std;
  8. int main()
  9. {
  10.     const int arrSize = 10;
  11.     //int arr[arrSize] = { 6,1,4,2,8,9,11,3,2,1 };
  12.     //int arr[arrSize] = { 1,1,1,2,2,9,11,1,2,1 };
  13.     //int arr[arrSize] = { 1,2,3,4,5,6,7,8,9,10 };
  14.     //int arr[arrSize] = { 1,2,3,4,5,6,7,9,8,7 };
  15.     //int arr[arrSize] = { 10,9,8,7,6,5,4,3,2,1 };
  16.     int arr[arrSize] = {0};
  17.     //int arr[arrSize] = { 7,3,2,6,5,1,7,3,8,1 };
  18.    
  19.     cout << "Enter value for " << 1 << " element: ";
  20.     cin >> arr[0];
  21.     cout << endl;
  22.  
  23.     for (int i = 0; i < arrSize; i++) { cout << arr[i] << " "; }; cout << endl;
  24.        
  25.     for (int newInsPos = 1; newInsPos < arrSize; newInsPos++)
  26.     {
  27.         cout << "Enter value for " << newInsPos+1 << " element: ";
  28.         cin >> arr[newInsPos];
  29.         cout << endl;
  30.  
  31.         for (int currInsPos = newInsPos; currInsPos > 0 && arr[currInsPos] < arr[currInsPos - 1]; currInsPos--)
  32.         {
  33.             int tmp = arr[currInsPos - 1];
  34.             arr[currInsPos - 1] = arr[currInsPos];
  35.             arr[currInsPos] = tmp;
  36.  
  37.             for (int i = 0; i < arrSize; i++) { cout << arr[i] << " "; }; cout << endl;
  38.         }
  39.     }
  40.  
  41.     for (int i = 0; i < arrSize; i++) { cout << arr[i] << " "; }; cout << endl;
  42.  
  43.     cout << "Enter search key: ";
  44.     int key;
  45.     cin >> key;
  46.     int left = 0, right = arrSize - 1, mid=0;
  47.     while(1)
  48.     {
  49.         cout << "Finding..";
  50.         mid = (left + right) / 2;
  51.         if (key == arr[mid]) { cout << "Found! Index is:" << mid << endl; break; };
  52.         if (key < arr[mid]) { right = mid - 1; cout << "left side" << endl; }
  53.         if (key > arr[mid]) { left = mid + 1; cout << "right side" << endl; }
  54.         if (left > right) { cout << "Not found!" << endl; break; };
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment