六种排序代码实现
###直接插入排序、折半插入排序、希尔排序、冒泡排序、快速排序、简单选择排序
#include<iostream>
#include<stdio.h>
using namespace std;
//输出
int printa(int a[], int n){
for(int i=0; i<n; i++)
cout<<a[i]<<" ";
}
//直接插入排序
void insertsort(int a[], int n){
for(int i=1; i<n; i++){
int temp = a[i];
int j=i-1;
while(j>=0 && a[j]>temp){
a[j+1] = a[j];
j--;
}
a[j+1] = temp;
printa(a, n);
printf("\n");
}
}
//折半排序
void BinInsertsort(int a[], int n){
int i, j, low, high, mid, temp;
for(i=1; i<n; i++){
if(a[i]<a[i-1]){
temp = a[i];
low = 0, high = i-1;
while(low <= high) {
mid = (low + high)/2;
if(temp < a[mid])
high = mid - 1;
else
low = mid + 1;
}
for(j=i-1; j>=high+1; j--)
a[j+1] = a[j];
a[high+1] = temp;
}
printa(a, n);
printf("\n");
}
}
//希尔排序
void shellsort(int a[], int n){
int i, j, d, temp;
d = n/2;
while(d){
for(i=d; i<n; i++){
temp = a[i];
j = i - d;
while( j>=0 && temp <a[i] ){
a[j+d] = a[j];
j = j - d;
}
a[j+d] = temp;
}
printa(a, n);
printf("\n");
d/=2;
}
}
//冒泡排序
void bubblesort(int a[], int n){
int i, j;
bool ex;
for( i=0; i<n-1; i++ ){
ex = false;
for( j=n-1; j>i; j--){
if( a[j] < a[j-1] ){
ex = true;
swap( a[j], a[j-1]);
printa(a, n);
printf("\n");
}
}
if(ex) return;
}
}
//快速排序
int partition(int a[], int s, int t){
int i = s, j = t, temp=a[i];
while(i<j){
while( j>i && a[j] >= temp) j--;
a[i] = a[j];
while( i<j && a[i] <= temp) i++;
a[j] = a[i];
}
a[i] = temp;
return i;
}
void quicksort( int a[], int s, int t){
int i;
if(s<t){
i = partition(a, s, t);
quicksort(a, s, i-1);
quicksort(a, i+1, t);
}
}
//简单选择排序
void selectsort(int a[], int n){
int i, j, k;
for( i=0; i<n-1; i++){
k = i;
for( j=i+1; j<n; j++)
if(a[j] < a[k] )
k = j;
if(k!=i){
swap(a[i], a[k]);
printa(a, 8);
printf("\n");
}
}
}
int main(){
int n=8;
int a[9]={0, 3, 2, 5, 8, 1, 9, 10};
//printf("直接插入排序结果如下:\n");
//insertsort(a, n);
//printf("折半插入排序结果如下:\n");
//BinInsertsort(a, n);
// printf("希尔排序结果如下:\n");
// shellsort(a, n);
// printf("冒泡排序结果如下:\n");
// bubblesort(a, n);
printf("快速排序结果如下:\n");
quicksort(a, 0, n-1);
printa(a, 8);
printf("\n");
// printf("简单选择排序结果如下:\n");
// selectsort(a, n);
}