Advertisement
Guest User

lab12-13

a guest
Apr 20th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.67 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3.  
  4. using namespace std ;
  5.  
  6. int main() {
  7.     int n = 10 ;
  8.     int arr[n+1] ;
  9.     arr[0] = 0 ;
  10.     for(int i = 1 ; i <= n ; i++){
  11.         arr[i] = rand() % 101 ;
  12.     }
  13.     int to_do = n-1, index ;
  14.     while ( to_do > 0 ){
  15.         index = 1 ;
  16.         while ( index <= to_do ){
  17.             if ( arr[index] > arr[index+1] ){
  18.                 int temp = arr[index] ;
  19.                 arr[index] = arr[index+1] ;
  20.                 arr[index+1] = temp ;
  21.             }
  22.             index++ ;
  23.         }
  24.         cout << "to_do = " << to_do << ": " ;
  25.         for(int i = 1 ; i <= n ; i++){
  26.             cout << arr[i] << " " ;
  27.         }
  28.         cout << endl ;
  29.         to_do-- ;
  30.     }
  31.  
  32.     int key ;
  33.     cout << "Enter search key: " ;
  34.     cin >> key ;
  35.  
  36.     int cou = 1, middle = 0, low = 1, high = n ;
  37.     while ( low <= high ){
  38.         bool ch = false ;
  39.         middle = (low + high)/2 ;
  40.         if ( key == arr[middle] ){
  41.             low = middle ;
  42.             high = middle ;
  43.             ch = true ;
  44.         }else if ( key < arr[middle]) {
  45.             high = middle - 1 ;
  46.         }else {
  47.             low = middle + 1 ;
  48.         }
  49.         cout << "Pass#" << cou << ":" ;
  50.         for(int i = 1 ; i <= n ; i++){
  51.             if ( low == i ){
  52.                 cout << "[" ;
  53.             }
  54.             cout << arr[i] ;
  55.             if ( high == i ){
  56.                 cout << "]" ;
  57.             }
  58.             cout << "  " ;
  59.         }
  60.         cout << endl ;
  61.         if ( ch == true ){
  62.             cout << "Found element " << key << " at index " << middle << endl ;
  63.             break ;
  64.         }
  65.         cou++ ;
  66.     }
  67.     return 0 ;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement