1. DirectInsert sort
直接插入排序,将所要排序的数字放到有序队列中
void DirectInsert(int a[10] , int num){
int i = 0;
int j ;
int temp ;
for( ; i < num ; i++){
for( j = i ; j > 0 ; j-- ){
if(a[j] < a[j-1]){
temp = a[j-1];
a[j-1] = a[j];
a[j] = temp ;
}
}
}
}
2 BiInsert sort
折半插入排序,使用折半查找法进行插入
void BiInsert(int a[10] , int num){
int i , j , low , high , mid , temp;
for( i = 1 ; i < num ; i++){
low = 0 ;
high = i-1 ;
while(low <= high){
mid = (low + high)/2;
if(a[mid] > a[i]){
high = mid -1 ;
}
else{
low = mid + 1;
}
}
temp = a[i];
for( j = i-1 ; j >= high + 1 ; --j){
a[j+1] = a[j];
}
a[high + 1] = temp ;
}
}
3. ShellSort
哈希排序,在一定步长的情况下进行排序,逐渐减小步长,直到步长为1.
void ShellSort(int a[10] ,int num){
int dk ;//step length
int i ;
int temp ;
int j ;
for(dk = num/2 ; dk >= 1 ; dk /= 2){//change the length of the step
for(i = dk ; i < num ; i++){//increase the num
if(a[i] < a[i-dk]){
temp = a[i];
for( j = i - dk ; j >= 0 && temp < a[j] ; j -= dk){//find the right location to insert
a[j + dk] = a[j];
}
a[j + dk] = temp ;//the right location to insert
}
}
}
}
4 Bubble Sort
冒泡排序,最大下沉
void BubbSort(int a[10] , int num) {
int i , j , temp;
for(i= 0 ; i < num ; i++){
for( j = 0 ; j < num - i - 1 ; j++){
if(a[j] > a[j+1]){
temp = a[j] ;
a[j] = a[j+1];
a[j+1] = temp ;
}
}
}
}
5 QuickSort
根据一个基点,将大于基点的值放在右边,小于基点的值放在左边
int Partition(int a[10],int low ,int high){
int pivot = a[low];
while(low < high){
while(low < high && a[high] > pivot)
--high;
a[low] = a[high];
while(low < high && a[low] < pivot)
++low ;
a[high] = a[low];
}
a[low] = pivot;
return low;
}
void FastSort(int a[10] , int low , int high){
if(low < high){
int pivotpos = Partition(a , low , high);
FastSort(a , low ,pivotpos -1);
FastSort(a , pivotpos+1 , high);
}
}
6 SelectionSort
选择未排序中最大的值与当前值对调
void ChooseSort(int a[10] , int num){
int i , j ,temp , loc ,min ;
for( i = 0 ; i < num ; i++){
min = a[i];
loc = i;
for( j = i ; j < num ; j++){
if(min > a[j]){
min = a[j];
loc = j;
}
}
a[loc] = a[i];
a[i] = min;
}
}
7 Heapsort
使用最大堆,将每次选出来的最大值放在最后一位。
//the exchange the number from i to the son to choose the big
void Adjustdown(int a[10] , int i , int num){
int temp = a[i];
int j ;
for( j = 2*i +1 ; j < num ; j = j*2 + 1){
if(j < num && a[j] < a[j+1]){
j++;
}
if(temp >= a[j])break;
else{
a[i] = a[j];
i = j ;
}
}
a[i] = temp;
}
//from the last father to the root to exchange the number
void BuildMaxHeap(int a[10] , int num){
int i ;
for( i = num / 2 ; i >= 0 ; i-- ){
Adjustdown( a , i ,num);
}
}
//put the min of the number to the last each time
void HeapSort(int a[10] , int num){
int temp;
BuildMaxHeap(a, num);
for(int m = num-1 ; m >= 0 ; m--){
temp = a[m];
a[m] = a[0];
a[0] = temp;
Adjustdown(a ,0, m-1);
}
}
//to insert the numeber and change the order
void Insert(int a[10] , int num , int e){
int temp = a[num];
int j , i ;
for(i = (num -1)/2 , j = num ; i >= 0 ; ){
if(temp > a[i]){
a[j] = a[i];
j = i ;
i = (i-1)/2;
}
a[i] = temp;
}
}