Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cstdlib>
- using namespace std ;
- int main() {
- int n = 10 ;
- int arr[n+1] ;
- arr[0] = 0 ;
- for(int i = 1 ; i <= n ; i++){
- arr[i] = rand() % 101 ;
- }
- int to_do = n-1, index ;
- while ( to_do > 0 ){
- index = 1 ;
- while ( index <= to_do ){
- if ( arr[index] > arr[index+1] ){
- int temp = arr[index] ;
- arr[index] = arr[index+1] ;
- arr[index+1] = temp ;
- }
- index++ ;
- }
- cout << "to_do = " << to_do << ": " ;
- for(int i = 1 ; i <= n ; i++){
- cout << arr[i] << " " ;
- }
- cout << endl ;
- to_do-- ;
- }
- int key ;
- cout << "Enter search key: " ;
- cin >> key ;
- int cou = 1, middle = 0, low = 1, high = n ;
- while ( low <= high ){
- bool ch = false ;
- middle = (low + high)/2 ;
- if ( key == arr[middle] ){
- low = middle ;
- high = middle ;
- ch = true ;
- }else if ( key < arr[middle]) {
- high = middle - 1 ;
- }else {
- low = middle + 1 ;
- }
- cout << "Pass#" << cou << ":" ;
- for(int i = 1 ; i <= n ; i++){
- if ( low == i ){
- cout << "[" ;
- }
- cout << arr[i] ;
- if ( high == i ){
- cout << "]" ;
- }
- cout << " " ;
- }
- cout << endl ;
- if ( ch == true ){
- cout << "Found element " << key << " at index " << middle << endl ;
- break ;
- }
- cou++ ;
- }
- return 0 ;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement