C++冒泡排序+折半查找

1.1冒泡排序

#include<iostream>
#include<stdio.h>
using namespace std;

void bubblesort(int a[],int len){
	int i,j;
	int temp;
	for(i=0;i<len;i++){
		for(j=0;j<len;j++){
			if(a[j-1]>a[j]){
				temp=a[j];
				a[j]=a[j-1];
				a[j-1]=temp;
			}
		}
	}
} 

int main(){
	int num;
	cin>>num;//输入数组个数 
	int a[num];
	for(int i=0;i<num;i++){//循环输入函数 
		cin>>a[i];
	}
	bubblesort(a,num);    //冒泡排序 
	
	for(int i=0;i<num;i++){//循环输出函数 
		cout<<a[i];
	}
	return 0;
}

1.2 折半查找

#include<iostream>
#include<stdio.h>
using namespace std;
//折半查找 时间复杂度 最好 nlogn  平均nlogn 最坏 O(n^2)
//目标一定要有序 
int Bsearch(int r[],int low,int high,int k){
	int mid;
	while(low<=high){
		mid=(low+high)/2;
		if(r[mid]==k){
			return mid;
		}
		else if(k<r[mid]){
			high=mid-1;
		}
		else if(k>r[mid]){
			low=mid+1;
		}
	}
}

int main(){
	int a[]={1,2,3,4,5,6};
	int high=sizeof(a)/sizeof(int);
	int k;
	cin>>k;
	cout<<Bsearch(a,0,high,k)<<endl; //返回查找元素的下表 
	return 0;
} 

 

1.3 冒泡+折半查找

#include<iostream>
#include<stdio.h>
using namespace std;
//冒泡+折半 
void bubblesort(int a[],int len){
	//冒泡 
	int i,j;
	int temp;
	for(i=0;i<len;i++){
		for(j=0;j<len;j++){
			if(a[j-1]>a[j]){
				temp=a[j];
				a[j]=a[j-1];
				a[j-1]=temp;
			}
		}
	}
} 
int Bsearch(int r[],int low,int high,int k){
	//目标一定要有序 
	int mid;
	while(low<=high){
		mid=(low+high)/2;
		if(r[mid]==k){
			return mid;
		}
		else if(k<r[mid]){
			high=mid-1;
		}
		else if(k>r[mid]){
			low=mid+1;
		}
	}
}


int main(){
	int num;
	cin>>num;
	int a[num];
	for(int i=0;i<num;i++){
		cin>>a[i];
	}
	bubblesort(a,num);//冒泡排序 
	cout<<"排序后:";
	for(int i=0;i<num;i++){
		
		cout<<a[i];
	}
	
	int k;
	cin>>k;
	int index=Bsearch(a,0,num,k);//折半查找 
	cout<<index;
	return 0;
} 




猜你喜欢

转载自blog.csdn.net/u013521274/article/details/102556690
今日推荐