标签:turn get start code cout lang include iostream search
#include <iostream>
void print_arrs(const int *, int N);
void sort_arrs(int *pInt, int N);
constexpr int COUNT = 10;
int search_data(const int *pInt, int N, int k);
int main() {
int arr[] = {1, 3, 5, 7, 6, 2, 4, 9, 8, 0};
std::cout << "排序前:" << std::endl;
print_arrs(arr, COUNT);
sort_arrs(arr, COUNT);
std::cout << "排序后:" << std::endl;
print_arrs(arr, COUNT);
int index = search_data(arr, COUNT, 9);
std::cout << "the index is : " << index << std::endl;
std::cin.get();
return 0;
}
/**
* 二分查找
* @param pInt
* @param N
* @param k
* @return
*/
int search_data(const int *const pInt, int N, int k) {
for (int start = 0, end = N, mid = N / 2; start <= end; mid = (start + end) / 2) {
if (pInt[mid] < k) {
start = ++mid;
} else if (pInt[mid] > k) {
end = --mid;
} else {
return mid;
}
}
return -1;
}
/**
* 插入排序
* @param pInt
* @param N
*/
void sort_arrs(int *const pInt, int N) {
for (int i = 1; i < N; ++i) {
int temp = pInt[i];
for (int j = i - 1; j >= 0 && pInt[j] > temp; --j) {
pInt[j + 1] = pInt[j];//移出空位
pInt[j] = temp;//新排落位
}
}
}
void print_arrs(const int *pInt, int N) {
for (int i = 0; i < N; ++i) {
std::cout << pInt[i] << "\t";
}
std::cout << std::endl;
}
标签:turn get start code cout lang include iostream search
原文地址:https://www.cnblogs.com/flowliver/p/14598390.html