C++之四种排序算法 插入 选择 冒泡 希尔

这篇博客详细介绍了四种基本的排序算法:插入排序、选择排序、冒泡排序和希尔排序的C++实现,并通过主函数调用展示了它们的排序过程。每种排序算法的效率和应用场景都有所不同,读者可以通过代码理解和比较它们的优劣。
摘要由CSDN通过智能技术生成
#include <iostream>
using namespace std;

/*插入排序*/
void InsertSort(int a[],int n){
	int i,j,temp;
	for(i=1;i<n;i++){
		temp=a[i];
		j=i-1;
		while(j>=0&&temp<a[j]){
			a[j+1]=a[j];
			j--;
		}
		a[j+1]=temp;
	}
	
	for(int k=0;k<n;k++){
		cout<<a[k];
	}
	
}
//选择排序 
void selectSort(int a[],int n){
	int i,j,k;
	int temp;
	for(i=0;i<n;i++){
		k=i;
		for(j=i+1;j<n;j++)
		 	if(a[k]>a[j])
		  	  k=j;
		temp=a[i];
		a[i]=a[k];
		a[k]=temp;
	}
	for(int k=0;k<n;k++){
		cout<<a[k];
	}
} 
//冒泡排序 
void bubleSort(int a[],int n){
	int i,j,flag;
	int temp;
	for(i=n-1;i>=1;i--){
		flag=0;
		for(j=1;j<=i;j++)
			if(a[j-1]>a[j]){
				temp=a[j];
				a[j]=a[j-1];
				a[j-1]=temp;
				
				flag=1;
			}
		if(flag==0)
		 {
			for(int k=0;k<n;k++){
				cout<<a[k];
			}	
		 }
	} 
}
//希尔排序 
void shellSort(int a[],int n){
	int j;
	for(int gap=n/2;gap>0;gap=gap/2){
		for(int i=gap;i<n;i++){
			int tmp=a[i];
			for(j=i;j>=gap&&tmp<a[j-gap];j=j-gap){
				a[j]=a[j-gap];
			}
			a[j]=tmp;
		}
	}
		for(int k=0;k<n;k++){
				cout<<a[k];
			}
} 

int main(){
	
	int a[]={1,5,6,4,7,8,9,3};
	int b[]={4,5,7,8,6,5,1,2,3};
	int c[]={4,5,7,8,6,5,1,2,3};
	int d[]={4,5,7,8,6,5,1,2,3};
	InsertSort(d,9);
	cout<<endl;
	shellSort(b,9);
	cout<<endl;
	selectSort(c,9);
	cout<<endl;
	bubleSort(a,8);

	system("pause");
	return 0;
} 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值