/*
快速排序:
1.以temp=a[SIZE/2]为基准,从右到左找到第一个比temp小的数,并交换位置,
从左到右找第一个比temp大的数,并交换位置,
2.递归排序a[0]到temp 和 temp到 a[SIZE]
*/
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define SIZE 10
void QuickSort(int *arr,int left,int right)
{
int f,t;
int rtemp,ltemp;
ltemp=left;
rtemp=right;
f=arr[(left+right)/2]; //以中位数为基准开始排序
while(ltemp<rtemp)
{
while(arr[ltemp]<f)
{
++ltemp;
}
while(arr[rtemp]>f)
{
--rtemp;
}
if(ltemp<=rtemp)
{
t=arr[ltemp];
arr[ltemp]=arr[rtemp];
arr[rtemp]=t;
--rtemp;
++ltemp;
}
}
if(ltemp==rtemp)
{
ltemp++;
}
if(left<rtemp)
{
QuickSort(arr,left,ltemp-1);
}
if(ltemp<right)
{
QuickSort(arr,rtemp+1,right);
}
}
void main()
{
int i;
int array[SIZE];
srand(time(NULL));
for(i=0;i<SIZE;i++)
{
array[i]=rand()%100+1; //1-100
}
printf(“排序前:\n”);
for(i=0;i<SIZE;i++)
{
printf("%d “,array[i]);
}
printf(”\n");
QuickSort(array,0,SIZE-1);
printf(“排序后:\n”);
for(i=0;i<SIZE;i++)
{
printf("%d “,array[i]);
}
printf(”\n");
}
博客介绍了快速排序算法的实现。以数组中间元素为基准,从右到左找比基准小的数、从左到右找比基准大的数并交换位置,然后递归排序基准左右部分。还给出了C语言代码,对随机生成的数组进行排序并输出排序前后结果。
1365

被折叠的 条评论
为什么被折叠?



