折半查找算法

二分查找:

实际的场景中,有些的数列是进过排序的,或者经过排序来呈现某种线性结构。
操作步骤:
 首先设置三个变量lownum,midnum,highnum分别保存数组元素的开始,中间和结尾。
假设有10个元素,开始令lownum = 0, highnum=9. midnum = (lownum + highnum) / 2 = 4  接着进行判断
 1、如果序号midnum的数组元素的值与x相等,表示查找到数据,返回midnum
 2、否则如果x < a[midnum], 表示要查找的数据x 位于lownum 与 midnum -1 之间,不需要再去查找midnum 与 highnum序号之间的元素,因此将highnum 改为 midnum - 1
    重新查找lownum与midnum -1之间的数据
 3、如果x > a[midnum] ,表示查找的数据位于midnum + 1 与 highnum 序号之间, 则不需要再去查找lownum 与 midnum之间的元素,因此将lownum改为midnum + 1,
重新查找midnum + 1 与 highnum 之间的数据。
4、逐步循环,如果lownum > highunm 时未找到目标数据,则表示该数组中没有该数据。



// BnarySearchFind.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <IOSTREAM>
#include <CSTDIO>
#include <CSTDLIB>
#include <CSTRING>
#include <CTIME>

using namespace std;

#define  N  15


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 *arr, int left, int right)
{
	int f,t;
	int rtemp,ltemp;
	
	ltemp = left;
	rtemp = right;
	
	f = arr[(left + right) / 2];		// 分界值
	while(ltemp < rtemp)
	{
		while(arr[ltemp] < f)	        // 查找左边值大于边界值
		{
			++ltemp;
		}
		while(arr[rtemp] > f)			// 查找右边值大于边界值
		{
			--rtemp;
		}
		if(ltemp <= rtemp)				// 交换数据位置
		{
			t = arr[ltemp];
			arr[ltemp] = arr[rtemp];
			arr[rtemp] = t;
			--rtemp;
			++ltemp;
		}
	}
	if (ltemp == rtemp)
	{
		ltemp ++;
	}
	if (left < rtemp)
	{
		QuickSort(arr,left,ltemp - 1);		// 递归
	}
	if (ltemp < right)
	{
		QuickSort(arr, rtemp + 1, right);
	}
}




int main(int argc, char* argv[])
{

	int x,n, i;
	int array[N];
	
	srand(time(NULL));
	for (i = 0;i < N; i++)
	{
		array[i] = rand() /1000 + 100;
	}
	
	cout<<"before search -------------"<<endl;
	for (i = 0; i < N; i++)
	{
		cout<<array[i]<<" ";
	}
	cout<<endl;

	QuickSort(array, 0, N-1);
	cout<<"sort------------------------: "<<endl;
	for (i = 0; i < N; i++)
	{
		cout<<array[i]<<" ";
	}
	cout<<endl;
		
	cout<<"enter you want to fund: "<<endl;
	fflush(stdin);
	cin>>x;
	
	n =	BinarySearchFun(array, N, x);
	

	if (n < 0)
	{
		cout<<"not found!"<<endl;
	}
	else
	{
		cout<<"data "<<x<<" at array "<<n + 1<<endl;
	}
	return 0;
}

/*
  before search -------------
  118 122 117 121 116 110 113 113 127 122 132 108 128 118 102
  sort------------------------:
  102 108 110 113 113 116 117 118 118 121 122 122 127 128 132
  enter you want to fund:
  117
	data 117 at array 7
 */










  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值