注:二分查找法有个问题,一组数字中有多个一样的数值时,其返回的下标位置不一样是数组中第一次出现的线标位置。
运行结果:
Enter digit numbers less than 10: -5 5 -5 33 -10 4 1 33 5
After sort: -10 -5 -5 1 4 5 5 33 33
Enter you want to find number: -5
Found it, the index is: 1
Enter digit numbers less than 10: -5 5 -5 33 -10 4 1 33 5
After sort: -10 -5 -5 1 4 5 5 33 33
Enter you want to find number: 5
Found it, the index is: 6
search.cpp
#include <iostream>
const int SIZE = 10;
void fillArray(int a[], int& usedSize);
void insertSort(int a[], const int& usedSize);
void show(int a[], const int& usedSize);
bool findVal(int a[], int first, int last, int& pos, const int& find);
int main() {
using std::cout;
using std::cin;
int usedSize = 0, pos, find;
int a[SIZE];
cout << "Enter digit numbers less than 10: ";
fillArray(a, usedSize);
cout << "After sort: ";
insertSort(a, usedSize);
show(a, usedSize);
cout << "Enter you want to find number: ";
cin >> find;
if (findVal(a, 0, usedSize - 1, pos, find))
cout << "Found it, the index is: " << pos << '\n';
else
cout << "Not found.\n";
return 0;
}
void fillArray(int a[], int& usedSize) {
using std::cin;
char c;
for (int i = 0; i < SIZE && (c = cin.get()) != '\n'; i++) {
cin.putback(c);
cin >> a[i];
usedSize++;
}
}
void insertSort(int a[], const int& usedSize) {
int temp, i, j;
for (i = 1; i < usedSize; i++) {
temp = a[i];
for (j = i - 1; j >= 0 && temp < a[j]; j--)
a[j + 1] = a[j];
a[j + 1] = temp;
}
}
void show(int a[], const int& usedSize) {
using std::cout;
for (int i = 0; i < usedSize; i++) {
cout << a[i] << ' ';
}
cout << '\n';
}
bool findVal(int a[], int first, int last, int& pos, const int& find) {
int mid;
while (first <= last) {
mid = (first + last) / 2;
if (a[mid] == find) {
pos = mid;
return true;
}
else if (a[mid] < find)
first = mid + 1;
else
last = mid - 1;
}
return false;
}