內部排序演算法
阿新 • • 發佈:2018-12-25
typedef struct{ int key; int Info; }RedType; typedef struct{ RedType* r; int length; }Sqlist; void InsertSort(Sqlist &L); void BinInsertSort(Sqlist &L); void ShellInsert(Sqlist &L); void BubbleSort(Sqlist &L); /*快速排序*/ int Partition(Sqlist &L, int low, inthigh); void Qsort(Sqlist &L, int low, int high); void QuickSort(Sqlist &L); /*快速排序*/ int main() { /*測試*/ Sqlist L; //int a[] = {12,23,45,1,7,2,99,4,3,2},i; int a[] = {99,45,23,12,7,4,3,2,2,1},i; /*正序:1 2 2 3 4 7 12 23 45 99*/ L.r = (RedType*)malloc(10*sizeof(RedType)); for(i = 0;i < 10;i++) { L.r[i].key = a[i]; } L.length = i; QuickSort(L); for (i = 0;i < 10;i++) { printf("%d ",L.r[i].key); } return 0; } void InsertSort(Sqlist &L) { /*插入排序*/ int i,j; RedType tmp; for (i = 1;i < L.length;i++) {if (L.r[i-1].key > L.r[i].key) { tmp = L.r[i]; /*注意迴圈終止條件*/ for (j = i-1;j >= 0 && L.r[j].key > tmp.key;j--) { L.r[j+1] = L.r[j]; } L.r[j+1] = tmp; } } } void BinInsertSort(Sqlist &L) { /*折半插入排序*/ int i,j,high,low,mid; RedType tmp; for (i = 1;i < L.length;i++) { if (L.r[i-1].key > L.r[i].key) { tmp = L.r[i]; low = 0; high = i-1; while (low <= high) { /*1*/ /*注意終止條件*/ mid = (low+high)/2; if (L.r[mid].key > tmp.key) { /*2*/ high = mid-1; } else { low = mid+1; } } for (j = i - 1; j >=high + 1; j--) { /*3*/ L.r[j+1] = L.r[j]; } L.r[high+1] = tmp; /*三個條件相互影響*/ } } } void ShellInsert(Sqlist &L) { /*希爾排序*/ int i,j,d; RedType tmp; d = L.length/2; while(d >= 1) { for (i = d;i < L.length;i++) { /*對d組輪流進行一次插入*/ if (L.r[i-d].key > L.r[i].key) { tmp = L.r[i]; for(j = i - d;j >= 0 && L.r[j].key > tmp.key;j-=d) { L.r[j+d] = L.r[j]; } L.r[j+d] = tmp; } } /*對d組進行插入排序,但在這個演算法中每一組的插入排序不是連續進行*/ d = d/2; } } void BubbleSort(Sqlist &L) { /*氣泡排序*/ int i,j; RedType tmp; for (i = 1;i < L.length;i++) { /*共需要進行n-1趟冒泡*/ for (j = L.length-1;j >= i;j--) { /*第一趟冒到0,第二趟冒到1...*/ if(L.r[j].key < L.r[j-1].key) { tmp = L.r[j]; L.r[j] = L.r[j-1]; L.r[j-1] = tmp; } } } } /*快速排序*/ int Partition(Sqlist &L,int low,int high) { RedType pivot = L.r[low]; while(low < high) { while (low < high && L.r[high].key >= pivot.key) { /*注意<=*/ high--; } L.r[low] = L.r[high]; while (low <high && L.r[low].key <= pivot.key) { low++; } L.r[high] = L.r[low]; /*交換L.r[high]和L.r[low]的優化*/ } L.r[low] = pivot; return low; } void Qsort(Sqlist &L,int low, int high) { int local; if (low < high) { local = Partition(L, low, high); Qsort(L, low, local-1); Qsort(L, local+1, high); } } void QuickSort(Sqlist &L) { Qsort(L, 0, L.length-1); } /*快速排序*/