算法概覽:
插入排序
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int a[7]={12,5,2,6,4,8,7}; //定義一個需要排列的數組
int i ,temp,p; //定義三個變量
for(i=1;i<7;i++){
//從數據第二位開始取對比數,進行對比,直至數組最後一位結束循環
temp=a[i]; //取第一個對比數
p = i-1;
while(p>=0 && temp<a[p]) //尋找對比數大於所認定的排序的位置
{
a[p+1]=a[p]; //後移一位
p--; //與需要對比的數組前一位繼續對比
}
a[p+1]=temp; //將對比數插入對應位置
}
for(i=0;i<7;i++){ //循環輸出數組
printf("%d\n",a[i]);
}
}
SHELL排序
void shellSort(int a[],int n){
int gap,i,j,temp;
for(gap=n/2;gap>0;gap/=2){
for(i=gap;i<n;i++){
for(j=i-gap;j>=0 && a[j]>a[j+gap];j-=gap){
temp = a[j];
a[j] = a[j+gap];
a[j+gap] = temp;
}
}
}
}
冒泡排序
void buble_sort(int a[],int n){
int temp;
for(int i=0; i<n-1; i++){
for(int j=0; j<n-1-i; j++){
if(a[j] > a[j+1]){
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp ;
}
}
}
}
快速排序算法
void quick_sort(int a[],int low,int high){
int i = low; //定義低位
int j = high; //定義低位
int temp =a[i]; //取出對比數
if(low<high){
while(a[j]>=temp && i<j){j--;} //從後往前掃描,尋找比對比數temp小的數
a[i]=a[j];
while(a[i]<=temp && i<j){i++;} //從前往後掃描,尋找比對比數temp大的數
a[j]=a[i];
a[i] = temp; /*當在當組內找完一遍以後就把中間數temp迴歸*/
//一分爲二,重複調用(第一部分小於第一部分)
quick_sort(a,low,i-1); //遞歸調用
quick_sort(a,i+1,high);//遞歸調用
}else{
return ;
}
}