-
Notifications
You must be signed in to change notification settings - Fork 18
/
8_2折半查找.cpp
60 lines (55 loc) · 1.26 KB
/
8_2折半查找.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
//8_2
//ÕÛ°ë²éÕÒ
void BinSearch(int x,int arr[],int len){
int i = 0,j = len,k = (i + j)/2;
while(i <= j){
k = (i + j) / 2;
if (arr[k] > x){//search the left side
j = k-1;
}
else if (arr[k] < x){//search the right side
i = k+1;
}
else{
cout << "the number you search is " << x << ",the index of it is " << k << endl;
return;
}
}
cout << "the number you search doesn't exist" << endl;
return ;
}
void BubbleSort(int arr[],int len){
int i,j,tmp;
for (i=0;i<len;i++){
for (j=i;j<len;j++){
if (arr[i] > arr[j]){
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
return ;
}
int main(){
int arr[10] = {21,32,2,4,56,9,10,8,7,67};
int a[10] = {21,32,2,4,56,9,10,8,7,67};
int len = sizeof(arr) / sizeof(int);
int x ;
BubbleSort(arr,len);
cout << "input the number you want to search:" ;
cin >> x;
while(x>0){
BinSearch(x,a,len);
cin >> x;
}
cout << "exit";
return 0;
}