Advertisement
Felanpro

Fast method to find index of number in array

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