# 常用排序算法代码测试

#include <stdio.h>
#define N 10  //测试数组长度
//交换变量值
void swap(int *a,int *b)
{

int t;
t=*a;
*a=*b;
*b=t;
}
//打印一次排序结果
void printResult(int a[],int n)
{
int i;
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
//直接插入排序
void InsertSort(int L[],int length)
{
int i,j;
for(i=1;i<length;i++){
j=i;
if(L[j]<L[i-1]){
int temp=L[j];
while(temp<L[j-1]&&j!=0){
L[j]=L[j-1];
j--;
}
L[j]=temp;
}
printResult(L,length);
}
}
//冒泡排序
void BubbleSort(int L[],int length)
{
int i,j;
for(i=0;i<length-1;i++){
for(j=1;j<length;j++)
if(L[j]<L[j-1])
{
swap(L+j,L+j-1);
}
printResult(L,length);
}
}
//选择排序
void SelectSort(int L[],int length)
{
int i,j,t;
for(i=0;i<length;i++){
t=i;
for(j=i+1;j<length;j++){
if(L[j]<L[t]) t=j;
}
if(t!=i){
swap(L+i,L+t);
}
printResult(L,length);
}

}

void Shell(int L[],int d)
{
int i,j,t;
int temp;
for(i=d;i<N;i++){
if(L[i]<L[i-d]){
temp=L[i];
j=i;
while(j-d>=0&&temp<L[j-d]){
L[j]=L[j-d];
j-=d;
}
L[j]=temp;
}
printResult(L,N);
}
}
//希尔排序
void ShellSort(int L[],int d)
{
while(d>=1){
printf("d=%d\n",d);
Shell(L,d);
d/=2;
}

}

void Merge(int L[],int head,int mid,int tail)
{
int T[N]={0};
int i=0,j=mid+1,k=0;
while((head+i)<=mid&&j<=tail){
if(L[head+i]<L[j]){
T[k++]=L[head+i];
i++;
}else{
T[k++]=L[j++];
}
}
while((head+i)<=mid){
T[k++]=L[head+i];
i++;
}
while(j<=tail)T[k++]=L[j++];
for(i=0;i<k;i++)L[head+i]=T[i];
printResult(L,N);
}
//归并排序
void MergeSort(int L[],int head,int tail)
{
int mid=0;
if(head<tail){
mid=(head+tail)/2;
MergeSort(L,head,mid);
MergeSort(L,mid+1,tail);
Merge(L,head,mid,tail);
}
}

int Partition(int L[],int low,int high)
{
int pivot=L[low];
int temp;
while(low<high){
while(low<high && L[high]>=pivot){
high--;
}
swap(&L[low],&L[high]);
while(low<high && L[low]<=pivot){
low++;
}
swap(&L[low],&L[high]);
}
printResult(L,N);
return low;
}
//快速排序
void QuickSort(int L[],int low,int high)
{
if(low<high){
int head=low;
int tail=high;
int n=Partition(L,head,tail);
QuickSort(L,low,n);
QuickSort(L,n+1,high);
}

}

void HeapAdjust(int *a,int i,int size)
{
int max=i;
int lchild=2*i+1,rchild=2*i+2;
if(i<(size-1)/2){
if(lchild<size && a[lchild]>a[max]){
max=lchild;
}
if(rchild<size && a[rchild]>a[max]){
max=rchild;
}
if(i!=max){
swap(a+i,a+max);
HeapAdjust(a,max,size);
}
}
}
void BuildHeap(int *a,int size)
{
int i;
for(i=size/2-1;i>=0;i--){
HeapAdjust(a,i,size);
}
}
//堆排序
void HeapSort(int *a,int size)
{
int i;
BuildHeap(a,size);
for(i=size-1;i>=0;i--){
swap(a,a+i);
HeapAdjust(a,0,i-1);
printResult(a,size);
}
}

void main()
{
int a[10]={5,9,2,6,5,2,4,10,8,3};
//InsertSort(a,10);
//BubbleSort(a,10);
//SelectSort(a,10);
//ShellSort(a,3);
//MergeSort(a,0,9);
//QuickSort(a,0,9);
HeapSort(a,10);

}



07-28 1265

08-19 817
07-19 2万+
12-12 1012
05-28 1959
07-02 920
11-02 1558
10-24 1万+
04-24 1万+
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客