快速排序
#include<stdio.h>
int A[10]={7,4,1,8,5,2,9,6,3,0};
void QuickSort(int A[],int low,int high)
{
int temp;
int i=low,j=high;
if(low<high)
{
temp=A[low];
while(i<j)
{
while(j>i&&A[j]>=temp) --j;
if(i<j)
{
A[i]=A[j];
++i;
}
while(i<j&&A[i]<temp) ++i;
if(i<j)
{
A[j]=A[i];
--j;
}
}
A[i]=temp;
QuickSort(A,low,i-1);
QuickSort(A,i+1,high);
}
}
int main()
{
for(int i=0;i<10;i++)
{
printf("%d ",A[i]);
}
printf("\n");
QuickSort(A,0,9);
for(int i=0;i<10;i++)
{
printf("%d ",A[i]);
}
printf("\n");
}
堆排序:
#include<stdio.h>
void Sift(int R[],int low,int high)
{
int i=low,j=2*i;
int temp=R[i];
while(j<=high)
{
if(j<high&&R[j]<R[j+1])
++j;
if(temp<R[j])
{
R[i]=R[j];
i=j;
j=2*i;
}
else break;
}
R[i]=temp;
}
void heapSort(int R[],int n)
{
int i;
int temp;
for(i=n/2;i>=0;--i)
Sift(R,i,n);
for(i=n;i>=1;--i)
{
temp=R[0];
R[0]=R[i];
R[i]=temp;
Sift(R,0,i-1);
}
}
int main()
{
int A[20]={7,4,1,8,5,2,0,9,6,3,11,14,17,18,15,12,10,19,16,13};
heapSort(A,19);
for(int i=0;i<20;i++)
{
printf("%d ",A[i]);
}
printf("\n");
}
归并排序
#include<stdio.h>
#include<stdlib.h>
void merge(int *p,int low,int mid,int high)
{
int i,k;
int* temp = (int*)malloc((high-low+1)*sizeof(int));//合并空间
int start1 = low;
int end1 = mid;
int start2 = mid+1;
int end2 = high;
//比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置
for (k = 0;start1<=end1 && start2<=end2;k++)
{
if (p[start1]<p[start2])
temp[k] = p[start1++];
else
temp[k] = p[start2++];
}
//检测剩余项,若有剩余,直接拷贝出来粘到合并序列尾
while (start1<=end1)
temp[k++] = p[start1++];
while (start2<=end2)
temp[k++] = p[start2++];
//将排好序的数组拷贝到原数组
for (i = 0;i<high-low+1;i++)
p[low+i] = temp[i];
//合并过程
printf("%d:",mid);
for (i = 0;i<high-low+1;i++)
printf("%d ",p[low+i]);
printf("\n");
free(temp);
}
void merge_sort(int*p,int low,int high)
{
int mid = (low+high)/2;
if (low <high)
{
merge_sort(p,low,mid);
merge_sort(p,mid+1,high);
merge(p,low,mid,high);
}
}
int main()
{
int A[10]={7,4,1,8,5,2,0,9,6,3};
merge_sort(A,0,9);
for(int i=0;i<10;i++)
{
printf("%d ",A[i]);
}
printf("\n");
}