冒泡,选择,插入,希尔,快速,归并
选择类的排序:选择排序,堆排序
交换类的排序:冒泡,快排
#include <stdio.h>
#include<stdbool.h>
#include<stdlib.h>
#define swap(a,b) {typeof(a) t=(a);a=b;b=t;}
#define LEN 15
typedef void (*SortFP)(int *,int );
void show(int *,int );//冒泡1
void bubble_sort(int *arr,int n)
{bool flag=true;for(int i=0;i<n-1&&flag;i++ ){flag=false;for(int j=0;j<n-i-1;j++){if(arr[j]>arr[j+1]){int temp=arr[j];arr[j]=arr[j+1];arr[j+1]=temp;flag=true;}}}show(arr,n);printf(":%s\n",__func__);
}
//选择1
void Select_sorting(int *arr,int n)
{bool flag=true;for(int i=0;i<n-1&&flag;i++){flag=false;int temp=i;for(int j=i+1;j<n;j++){if(arr[temp]>arr[j])temp=j;flag=true;}if(temp!=i){int temp1=arr[temp];arr[temp]=arr[i];arr[i]=temp1;} }show(arr,n);printf(":%s\n",__func__);
}//插入1
void insertion_Sort(int *arr,int n)
{int i;for(int j=1;j<n;j++){int temp=arr[j];for( i=j;i>0&&arr[i-1]>temp;i--){arr[i]=arr[i-1];}arr[i]=temp;}
}//插入2
void insertion_Sort2(int *arr,int n)
{for(int i=1,j=0;i<n;i++){int val=arr[i];for( j=i;j>0&&arr[j-1]>val;j--){arr[j]=arr[j-1]; }if(j!=i) arr[j]=val;}show(arr,n);printf(":%s\n",__func__);}
//希尔1
void shell_sort(int *arr,int n)
{int i; for(int d=n>>1;d>0;d=d>>1){for(int j=d;j<n;j=d+j){int temp=arr[j]; for( i=j;i>=d&&arr[i-d]>temp;i-=d){arr[i]=arr[i-d]; }arr[i]=temp;}}
}
//希尔2
void shell_Sort2(int *arr,int n)
{for(int d=n/2;d>0;d/=2){for(int i=d,j=0;i<n;i++){int val=arr[i];for( j=i;j>=d&&arr[j-d]>val;j=j-d){arr[j]=arr[j-d]; }if(j!=i) arr[j]=val;}}show(arr,n);printf(":%s\n",__func__);} //归并1
void Merge_sort(int *arr,int *reg,int start,int end)
{if(start>=end )return ;int len=end-start;int mid=(len>>1)+start;int start1=start,end1=mid;int start2=mid+1,end2=end;Merge_sort(arr,reg,start1,end1);Merge_sort(arr,reg,start2,end2);int k=start;while(start1<=end1&&start2<=end2){reg[k++]=arr[start2]>arr[start1]?arr[start1++]:arr[start2++];}while(start1<=end1){reg[k++]=arr[start1++]; }while(start2<=end2){reg[k++]=arr[start2++]; }for(k=start;k<=end;k++){arr[k]=reg[k] ;}}//快速1
void Quick_Sort(int *arr,int l,int h)
{if(l>=h) return ;int low=l;int high=h;int pivot=arr[low];while(low<high){while(low<high&&arr[high]>=pivot) high--; arr[low]=arr[high];while(low<high&&arr[low]<pivot)low++;arr[high]=arr[low];}arr[low]=pivot;Quick_Sort(arr,l,low-1);Quick_Sort(arr,low+1,h);}void quick_sort(int *arr,int len)
{Quick_Sort(arr,0,len-1);show(arr,len);printf(":%s\n",__func__);
}void show(int *arr,int n)
{for(int i=0;i<n;i++){printf("%d ",arr[i]); }printf("\n");
}int main(int argc,const char* argv[])
{int arr[LEN]={};SortFP sort[]={bubble_sort,Select_sorting,insertion_Sort2,shell_Sort2,quick_sort};for(int i=0;i<sizeof(sort)/sizeof(sort[0]);i++){for(int j=0;j<LEN;j++){arr[j]=rand()%100;printf("===");}printf("\n");show(arr,LEN);printf("排序前\n");sort[i](arr,LEN);
}//bubble_sort(arr,n); //冒泡//Select_sorting(arr,n);//选择排序//shell_sort(arr,n); //希尔排序//insertion_Sort(arr,n); //插入排序//quick_sort(arr,n);/*int reg[6]={};Merge_sort(arr,reg,0,n-1);//归并排序*/return 0;
}