Advertisement
Guest User

Untitled

a guest
May 23rd, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.69 KB | None | 0 0
  1. #include<iostream>
  2. #include<ctime>
  3. using namespace std;
  4.  
  5.  
  6. int binarySearch(double *vectorA, int n,double value)
  7. {
  8.     int index;
  9.     int left=0, right=n-1;
  10.    
  11.     while (left <= right)
  12.     {
  13.         index = (left + right) / 2;
  14.  
  15.         if (vectorA[index] == value) {
  16.  
  17.             return index;
  18.         }
  19.            
  20.  
  21.         if (vectorA[index] > value) {
  22.  
  23.             right = index - 1;
  24.         }
  25.            
  26.         else {
  27.             left = index + 1;
  28.  
  29.         }
  30.            
  31.     }
  32.  
  33.     return -1;
  34.  
  35. }
  36.  
  37.  
  38. void bubbleSort(double *vectorA,int n) //sortujemy elementy wektora(rosnaco) za pomoca sortowanie babelkowego
  39. {
  40.  
  41.     for (int i = 0; i<n; i++)
  42.         for (int j = 1; j<n - i; j++)
  43.             if (vectorA[j - 1]>vectorA[j])
  44.                
  45.                 swap(vectorA[j - 1], vectorA[j]);
  46.  
  47.  
  48.  
  49. }
  50. void setVectorValue(double*vectorA,int n)
  51. {
  52.  
  53.     for (int i = 0; i < n; i++)
  54.     {
  55.         vectorA[i] = rand() % 101; //uzupelniamy wektor wartosciami od 0 do 100
  56.  
  57.  
  58.     }
  59.  
  60. }
  61.  
  62. void showVector(double *vectorA, int n)
  63. {
  64.     for (int i = 0; i < n; i++)
  65.     {
  66.         cout << vectorA[i] << endl;
  67.     }
  68.  
  69.  
  70. }
  71.  
  72.  
  73. int main() {
  74.  
  75.     int n;
  76.     double value;
  77.     double *vectorA;
  78.     cout << "Podaj liczbe elementow wektora\n";
  79.     cin >> n;
  80.     vectorA = new double[n];
  81.     setVectorValue(vectorA,n);
  82.     cout << "Przed sortowaniem\n";
  83.     showVector(vectorA, n);
  84.     cout << endl;
  85.     cout << "Po sortowaniu\n";
  86.     bubbleSort(vectorA, n);
  87.  
  88.     showVector(vectorA, n);
  89.     cout << "Podaj wartosc szukanego elementu\n";
  90.     cin >> value;
  91.     if (binarySearch(vectorA, n, value) == -1)
  92.     {
  93.         cout << "Nie ma takiego elementu...Funkcja zwraca wartosc:\n";
  94.         cout << binarySearch(vectorA, n, value);
  95.         cout << endl;
  96.     }
  97.     else
  98.     {
  99.         cout << "Indeks szukanego  elementu  to...\n";
  100.         cout << binarySearch(vectorA, n, value);
  101.         cout << endl;
  102.     }
  103.    
  104.     system("pause");
  105.     return 0;
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement