#include <iostream> using namespace std; /******************** 插入类排序 ****************************/ //直接插入排序 //基本操作是将第i个记录插入到前面i-1个已排好的记录中. void InsSort(int a[],int length) { for(int i = 1;i <= length -1;i++) { int tmp = a[i]; int j = 0; for(j = i-1; j >= 0;j--) { if(tmp < a[j]) { a[j+1] = a[j]; } else { break; } } a[j+1] = tmp; } } //折半插入排序 void BinSort(int a[],int length) { for(int i = 1;i <= length - 1;i++) { int low = 0,high = i - 1; int tmp = a[i]; while(low < high) { int mid = (low + high)/2; if(tmp > a[mid]) { low = mid + 1; } else { high = mid - 1; } } for(int j = i - 1; j >= low;j--) { a[j+1] = a[j]; } a[low] = tmp; } } /******************** 交换类排序 ****************************/ //冒泡排序 void BubbleSort(int a[],int length) { bool bcontinue = true; for(int i = 0;i <= length -1&& bcontinue;i++) { bcontinue = false; for(int j = 0;j <= length - i -2;j++) { if(a[j] > a[j+1]) { int tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; bcontinue = true; } } } } //快速排序 void QuickSort(int a[],int low,int high) { if(low >= high) { return; } int left = low,right = high; int tmp = a[left]; while(left < right) { while(left < right && a[right] >= tmp) { right--; } if(left<right) { a[left] = a[right]; left ++; } while(left<right && a[left] < tmp) { left++; } if(left < right) { a[right] = a[left]; right--; } } a[left] = tmp; QuickSort(a,low,left-1); QuickSort(a,left +1,high); } /******************** 选择类排序 ****************************/ //简单选择排序 void SelectSort(int a[],int length) { for(int i = 0;i <= length -1 ; i++) { int k = i; for(int j = i+1;j <= length - 1;j++) { if(a[j] < a[k]) { k = j; } } if(k!= i) { int tmp = a[i]; a[i] = a[k]; a[k] = tmp; } } } void Print(int a[],int length) { for(int i = 0; i <= length - 1;i++) { cout <<a[i]<<" "; } cout <<endl; return ; } int main() { int a[] = {5,7,3,1,0,12,98,56,101,105,-5}; int length = sizeof(a)/sizeof(int); Print(a,length); cout <<length<<" 1# @@@@@@@@"<<endl; //InsSort(a,length); //BubbleSort(a,length); //SelectSort(a,length); //QuickSort(a,0,length-1); BinSort(a,length); cout <<length<<" 2# @@@@@@@@"<<endl; Print(a,length); return 0; }