数据结构-二分查找

89 阅读1分钟
#include <iostream> 
#include <cstdio>
#include <cstdlib>
#include <ctime>

using namespace std;
/*
折半查找:建立在有序表的基础上,这里使用快排对100个随机数排序 
*/

int partition(int a[], int low, int high){
	int pivot = a[low];
	while(low < high){
		while(low < high && a[high] >= pivot){
			high--;
		}
		a[low] = a[high];
		while(low < high && a[low] <= pivot){
			low++;
		}
		a[high] = a[low];
	}
	a[low] = pivot;
	return low;
} 

void QuickSort(int a[], int low, int high){
	if(low < high){
		int pivotpos = partition(a, low, high);
		QuickSort(a, low, pivotpos-1);
		QuickSort(a, pivotpos+1, high);
	}
}

int function(int left, int right, int k, int a[]){
	
	while(left <= right){
		int mid = (left + right)/2;
		
		if(k > a[mid]){
			left = mid+1;
			
		}
	
		else if(k == a[mid]){
			return mid;
		}
	
		else{
			right = mid - 1;
		}
	}
} 



int main(){
	int arr1[100];
	//这里使用100个随机数
	int n = 10;
	for(int i = 0; i<n ;i++){
		arr1[i] = rand();
	} 

	cout<<"100个随机数为:"<<endl;
	for(int i = 0; i<n; i++){
		cout<<arr1[i]<<" ";
	}cout<<endl;
	cout<<endl<<"100个随机数排序之后为:"<<endl;

	QuickSort(arr1, 0, n-1);
	partition(arr1, 0, n-1);
	
	for(int i = 0; i<n; i++){
		cout<<arr1[i]<<" ";
	}
	
	//二分查找 
	
	int left = 0;
	int right = n-1;
	int key = 18467;
	
	int count = function(left, right, key, arr1);
	
	cout<<endl<<endl;
	cout<<count+1;
	
	
	return 0;
}