C++ <二分查找法>

注:二分查找法有个问题,一组数字中有多个一样的数值时,其返回的下标位置不一样是数组中第一次出现的线标位置。
运行结果:

 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值