1.冒泡排序
BubblingSort.c
#include<stdio.h>
/**
冒泡排序是稳定排序
时间复杂度 O(N^2) 循环嵌套
时间花销太大
*/
int main(){
int array[5],i,j,temp;
printf("input 5 num:\n");
for(i=0;i<5;i++){
scanf("%d",&array[i]);
}
//排序
for(i=4;i>=0;i--)
for(j=0;j<i;j++){
//前一个大于后一个
if(array[j]>array[j+1]){
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
for(i=0;i<5;i++){
printf("%d\t",array[i]);
}
return 0;
}
2.桶排序
BucketSort.c
#include <stdio.h>
/**
桶排序是稳定排序
时间复杂度 O(N+M)
O(M+N+M+N)=O(2(M+N)) 常数可忽略 =>O(M+N)
桶排序是最快最简单的排序
空间花销大,适合数据量大的排序,数值又不大的数据 (密集)
*/
int main()
{
int max=1000,n,t,i,j;
int a[1000];
for(i=0;i<=1000;i++){
a[i]=0;//M
}
printf("num:");
scanf("%d",&n);
printf("space input:\n");
for(i=0;i<n;i++){//N
scanf("%d",&t);
a[t]++;
}
for(i=0;i<=1000;i++)//M
for(j=1;j<=a[i];j++){
printf("%d\t",i);//N
}
return 0;
}
3.快速排序
QuickSort.c
/**
快速排序增大交换距离,相同比较次数就只交换一次
例子:
12 2 4 1 5
冒泡排序:12比较5次,移动(交换)5次
快速排序:比较5次(后往前1次,前往后4次),移动(交换)1次
*/
void quickSort(int a[],int low,int high){
int start=low;
int end=high;
int j=a[low];//定义基点
int temp=0;
while(start<end){
//以后向前推进
while(start<end&&a[end]>=j)
end--;
if(a[end]<j){
temp=a[end];
a[end]=j;
j=temp;
}
//从前往后推进
while(start<end&&a[start]<=j)
start++;
if(a[start]>j){
temp=a[start];
a[start]=j;
j=temp;
}
}
if(low<start-1)
quickSort(a,low,start-1);
if(start+1<high)
quickSort(a,start+1,high);
}
int main(){
int a[5]={1,4,1,3,2},i;
quickSort(a,0,4);
for(i=0;i<5;i++){
printf("%d\t",a[i]);
}
return 0;
}