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
| #include<iostream> using namespace std; int find(int, int[], int); int find1(int, int[], int); bool add(int a[], int n); int main() { int a[] = { 22, 1, 66, 88, 44, 32, 64 }; if(add(a,7)) cout<<"采用二分算法得到的位置为:"<<find1(44,a,7); else cout<<"采用递增算法得到的位置为:"<<find(44,a,7); return 0; } int find(int m, int a[], int n) { for (int i = 0; i < n; i++) { if (a[i] == m) return i+1; } return -1; } int find1(int m, int a[], int n) { int min = 0, max = n - 1, i; while (min <= max) { i = (min + max) / 2; if (a[i] == m) {return i+1;} if (a[i] < m) {min = i + 1;} else max = i - 1; } return -1; } bool add(int a[], int n) { for (int i = 1; i < n; i++) { if (a[i] < a[i - 1]) return false; } return true; }
|