Advertisement
Felanpro

Find specific number in sorted array

Feb 22nd, 2019
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int main()
  6. {
  7.     // Search for a specific number in an array
  8.     int array[19] = {2, 5, 3, 8, 6, 4, 7, 1, 1, 3, 4, 8, 1, 3, 4, 1, 1, 1, 1};
  9.     //Searching for number 5;
  10.     int search_number = 1;
  11.     int temp;
  12.     int length = 19;
  13.  
  14.     //First we want to sort the array through bubble-sorting
  15.     for(int x = 0; x < length - 1; x++)
  16.     {
  17.         for(int y = x + 1; y < length; y++)
  18.         {
  19.             if(array[x] > array[y])
  20.             {
  21.                 temp = array[x];
  22.                 array[x] = array[y];
  23.                 array[y] = temp;
  24.             }
  25.         }
  26.     }
  27.  
  28.     for(int z = 0; z < length; z++)
  29.         cout << array[z] << " ";
  30.  
  31.     //system("cls");
  32.     cout << endl;
  33.  
  34.     //After sorting the array you can now do the method of finding the number
  35.     int variable = (length/2);
  36.     cout << variable << endl;
  37.     int middle = length/2;
  38.  
  39.     while(array[variable] != search_number)
  40.     {
  41.         if(array[variable] > search_number)
  42.         {
  43.             variable = variable/2;
  44.         }
  45.         else
  46.         {
  47.             variable = (variable / 2) + middle;
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement