查找排序是比較常用的算法,查找的方法很多這裏先介紹兩個最簡單的查找方法,順序表查找和折半查找。
順序查找(Sequential Search)又名線性查找,是最基本的查找技術,它的查找方式爲:從表中第一個(或最後一個)開始,最後逐個進行記錄的關鍵字和給定值做比較,若某個記錄的關鍵字和給定值相等,則查表成功,如查表找到第一個記錄,若關鍵字和給定值的比較都不等時,查找不成功。
折半查找(Binary Search)技術,又稱二分查找法,它的前提是線性表中的記錄必須是關鍵碼有序(通常爲從小到大),線性表必須纔有順序結構。
基本思想:在有序表中,取中鍵記錄爲比較對象,若給定值與中間值記錄相等,則查找成功,若給定值小於中間值,則對中間值的左邊部分遞歸,否則對其左邊部分做遞歸。(注意遞歸的出口爲,左邊值不小於右邊值)
以查找給定值爲11爲例
①:指向中點下標爲4,記錄爲15,大於給定值,將右界置爲4-1,繼續查找;
②:再次指向中點,下標爲2,記錄爲7,小於給定值,將左界置爲2+1,繼續查找。
③:此時,左右界下標均爲3,若下標3對應的記錄與給定值相等,則返回對應下標,否則左界置爲4,右界置爲2,繼續查找;
④:左界大於右界,退出循環,查找失敗返回0;
#include <iostream>
int Sequential_Search(int *a, int n, int k);
void quick_sort(int *s, int Left, int Right);
int binary_search(int *arr, int n, int key);
int main()
{
using namespace std;
int nInput[10] = { 2, 54, 32, 12, 43, 54, 32, 31, 24, 94};
cout << "The array is: ";
for (int i = 0; i < 9; i++)
{
cout << nInput[i] << " ";
}
cout << endl;
int result_1=Sequential_Search(nInput,9, 43);
cout <<"43 "<< result_1<< endl;
quick_sort(nInput,0,9);
int result_2 = binary_search(nInput, 9, 94);
cout << "The array is: ";
for (int i = 0; i < 9; i++)
{
cout << nInput[i] << " ";
}
cout << endl;
cout << "94 " << result_2 << endl;
cin.get();
return 0;
}
void quick_sort(int *s,int Left,int Right)
{
//快速排序
if (Left<Right)
{
int i = Left,j=Right,x=s[i];
while (i<j)
{
while (i<j&&s[j]>=x)
{
j--;
}
if (i<j)
{
s[i++] = s[j];
}
while (i<j&&s[i]<=x)
{
i++;
}
if (i < j)
{
s[j--] = s[i];
}
}
s[i] = x;
quick_sort(s, Left, i - 1);
quick_sort(s, i+1, Right);
}
}
int binary_search(int *arr,int n,int key)
{
//折半查找
int low = 0, high = n ,mid;
while (low<=high)
{
mid = (low + high) / 2;
if (key<arr[mid])
{
high = mid - 1;
}
else if (key>arr[mid])
{
low = mid + 1;
}
else
{
return mid;
}
}
return 0;
}
int Sequential_Search(int *arr, int n, int k)
{
//順序查找
for (int i = 0; i <= n; i++)
{
if (arr[i]==k)
{
return i;
}
}
return 0;
}
運行結果
要使用折半查找法,要保證數組元素有序,使用快速排序算法,這有介紹http://blog.csdn.net/avalon_y/article/details/50877759。