折半查找
有些数据序列是经过排序的,或者可以经过排序呈现某种线性结构,这样可以不用逐个比较查找,可以采用折半查找提高查找效率。
折半查找 (Binary Search
) 又称二分查找,要求数据序列呈线性结构,也就是经过排序的,对没有经过排序的,可以先通过排序算法进行排序,然后再执行折半查找。
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
void QuickSort(int *a, int left, int right); // 快速排序
int BinarySearchFun(int a[], int n, int x); // 折半查找
const int N = 10;
int x, n, i, j;
int array[N];
std::cout << "请输入排序前数组: " << std::endl;
for (i=0;i<N;i++)
{
std::cin >> array[i];
}
std::cout << std::endl;
QuickSort(array, 0, N-1);
std::cout << "快速排序之后的数组为: " << std::endl;
for (j=0;j<N;j++)
{
std::cout << array[j] << " ";
}
std::cout << std::endl;
std::cout << "输入要查找的数: ";
std::cin >> x;
n = BinarySearchFun(array, N, x);
if (n<0)
{
std::cout << "没有找到数据 " << x << std::endl;;
}
else
{
std::cout << "数据 " << x << " 位于数组的第 " << n+1 << " 个元素处." << std::endl;;
}
return 0;
}
int BinarySearchFun(int a[], int n, int x) // 折半查找
{
int mid, low, high;
low = 0;
high = n - 1;
while (low<=high)
{
mid = (low + high) / 2;
if (a[mid]==x)
{
return mid; // 找到
}
else if (a[mid]>x)
{
high = mid - 1;
}
else
{
low = mid + 1;
}
}
return -1; // 未找到
}
void QuickSort(int *a, int left, int right) // 快速排序算法
{
int f, t;
int ltemp, rtemp;
ltemp = left;
rtemp = right;
f = a[(left+right)/2];
while (ltemp<rtemp)
{
while (a[ltemp]<f)
{
++ltemp;
}
while (a[rtemp]>f)
{
--rtemp;
}
if (ltemp<=rtemp)
{
t = a[ltemp];
a[ltemp] = a[rtemp];
a[rtemp] = t;
--rtemp;
++ltemp;
}
}
if (ltemp==rtemp)
{
ltemp++;
}
if (left<rtemp)
{
QuickSort(a,left, ltemp-1);
}
if (ltemp<right)
{
QuickSort(a, rtemp+1, right);
}
}
import numpy as np
def QuickSort(value, left, right):
"""
Qucik Sort
:param value: random array
:param left: start
:param right: end
:return: quick array
"""
if left >= right:
return
mid = value[left] # 设定起始的基准元素
ltemp = left
rtemp = right
while (ltemp < rtemp):
while (ltemp < rtemp and value[rtemp] >= mid):
rtemp -= 1
value[ltemp] = value[rtemp]
while (ltemp < rtemp and value[ltemp] < mid):
ltemp += 1
value[rtemp] = value[ltemp]
value[ltemp] = mid
QuickSort(value, left, ltemp - 1)
QuickSort(value, ltemp + 1, right)
def BinarySeaechFun(value, n, x):
low = 0
high = n - 1
while (low <= high):
mid = (low + high) // 2
if value[mid] == x:
return mid
elif value[mid] > x:
high = mid - 1
else:
low = mid + 1
else:
return False
return mid
def main():
list = [10, 2, 5, 6, 7]
print("排序前的数组为: ")
print(list)
left = 0
right = len(list) - 1
QuickSort(list, left, right)
print("快速排序后的数组:")
print(list)
x = 5
n = len(list)
idx = BinarySeaechFun(list, n, x)
print("数据 %d 位于数组的第 %d 个元素处."%(x, idx+1))
if __name__ == "__main__":
main()