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;
}