#include<iostream>
using namespace std;
int Partition (int arr[],int start_,int end_);
//先进行快排,将我们的数组进行排序,再进行二分搜索
void quickSort(int arr[],int startV,int endV){
if(startV<endV){
int mid=Partition (arr,startV,endV);
quickSort(arr,startV,mid-1);
quickSort(arr,mid+1,endV);
}
}
//获取中间的数
int Partition (int arr[],int start_,int end_){
int value=arr[start_];
while(start_<end_){
while(start_<end_&&arr[end_]>=value) end_--;
arr[start_]=arr[end_];
while(start_<end_&&arr[start_]<=value) start_++;
arr[end_]=arr[start_];
}
arr[end_]=value;
return end_;
}
//二分搜索
int binarySearch(int arr[],int len,int target){
int left=0;
int right=len-1;
int mid;
while(left<=right){
mid=(left+right)/2;
if(target<arr[mid]){
right=mid-1;
}else if(target>arr[mid]){
left=mid+1;
}else if(target==arr[mid]){
return mid;
}
}
return -1;
}
int main(){
int len; //数组长度
int target; //目标数字
cout<<"请输入长度:";
cin>>len;
int* arr=new int[len];
cout<<endl<<"请输入数字:";
for(int i=0;i<len;i++){
cin>>arr[i];
}
cout<<endl<<"请输入目标数字:";
cin>>target;
quickSort(arr,0,len-1);
cout<<"排序后的数组: ";
for(int i=0;i<len;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
cout<<target<<"在排序后的数组第 "<<binarySearch(arr,len,target)+1<<" 个";
}
快排和二分搜索的实验记录
最新推荐文章于 2021-05-12 17:09:07 发布