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

it2025-05-05  19

#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)