初始化int类型data1[ ]={1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20}先使用任意一种算法对其排序提示用户输入一个数字,再折半查找

初始化int类型data1[ ]={1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20}先使用任意一种算法对其排序提示用户输入一个数字,应用折半查找函数模板找出它的位置。#include
using namespace std;
template
void mySwap(T&x, T&y) {
T temp = x;
x = y;
y = temp;
}
template
void selectionSort(T a[], int n) {
for (int i = 0; i < n - 1; i++) {
int leastIndex = i;
for (int j = i + 1; j < n; j++)
if (a[j] < a[leastIndex])
leastIndex = j;
mySwap(a[i], a[leastIndex]);
}
}
template
int BinSearch(const T list[], int n, const T & key)
{
int low = 0;
int high = n - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (key == list[mid])
return mid;
else if (key>list[mid])
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main()
{
int key, n = 20;
int data1[] = { 1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20 };
selectionSort(data1, n);
for (int i = 0; i < n; i++)
{
cout << data1[i]<<",";
}
cout << endl;
cout << “Please input a key:” << endl;
cin >> key;
cout << BinSearch(data1, n, key) << endl;
}

你可能感兴趣的:(初始化int类型data1[ ]={1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20}先使用任意一种算法对其排序提示用户输入一个数字,再折半查找)