Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.49 KB | None | 0 0
  1.  
  2. #define MAX 100
  3. #include <iostream>
  4. #include <string>
  5. #include <cstdlib>
  6. #include <ctime>
  7. #include <cmath>
  8. #include <iomanip>
  9. #include <time.h>
  10. #include <algorithm>
  11. using namespace std;
  12.  
  13. int zamiany= 0;
  14. int porownania= 0;
  15. int main()
  16. {
  17.     srand(time(NULL));
  18.  
  19.     int tab[MAX];
  20.  
  21.     for (int i = 0; i < MAX; i++) //uzupełnianie tablicy losowymi wartościami
  22.     {
  23.         tab[i] = rand() % 1999;
  24.     }
  25.  
  26.  
  27.     cout <<"Posortowana tablica: " << endl << endl;
  28.     sort(tab,tab+MAX);              //sortowanie tablicy
  29.    
  30.     for (int i = 0;i < MAX;i++) {
  31.         cout << tab[i] << " ";                      // wyświetlenie tablicy
  32.     }
  33.         cout << endl << endl;
  34.  
  35.     int liczba, n = MAX, l, p, s,x=0;
  36.  
  37.     cout << "Zawartosc tablicy:\n";
  38.     cout << endl;
  39.     for (int i = 0; i < n; i++)
  40.     cout << "tab [" << i << "] = " << tab[i] << endl;
  41.     cout << "Podaj jaki element znalezc: ";
  42.     cin >> liczba;
  43.     l = 0;
  44.     p = n-1;
  45.     int licznik = 0;
  46.     while (true)
  47.     {
  48.         licznik++;
  49.  
  50.         if (l > p)
  51.         {
  52.             cout << "Nie odnaleziono szukanego elementu" << endl;
  53.             break;
  54.         }
  55.         s = (l+p)/2;
  56.         if (tab[s] == liczba)
  57.         {
  58.             cout << "Odnaleziono liczbe " << liczba << " pod indeksem " << s << endl;
  59.             break;
  60.         }
  61.  
  62.         if (tab[s] < liczba)
  63.             l = s+1;
  64.         else
  65.             p = s-1;
  66.  
  67.  
  68.     }
  69.     cout << "Ilosc iteracji: " << licznik << endl;
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement