Advertisement
Guest User

Untitled

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