# 快速排序如何写

0
[已解决问题] 解决于 2013-10-26 21:50

xiaoleilei | 初学一级 | 园豆：80

0

1

0
```  快速排序主要是分而治之的思想，下面第一个方法可以不变，永远的框架

static void F2(int[] a, int n, int m)
{
int position = 0;
if (n < m)
{
position = Partition(a, n, m);
F2(a, n, position-1);
F2(a, position+1, m);
}
}

static int Partition(int[] a, int n, int m)
{
int t = 0;
int flag = n;
int p1 = n+1;
int p2 = m;

while (p1 <= p2 && p1 <= m && p2 >= n) //移动条件
{
if (a[p1]>=a[flag]) //以第一个数为标准分成两部分
{
if (a[p2] < a[flag])
{
t = a[p1];
a[p1] = a[p2];
a[p2] = t;
p1++;
p2--;
}
else p2--;
}
else p1++;
}

t = a[p2];
a[p2] = a[flag];
a[flag] = t;

return p2;
}

```
View Code

gw2010 | 园豆：1487 (小虾三级) | 2013-10-15 15:39
0

```#include <stdio.h>
#include <time.h>
#include <string.h>

int partion(int num[], int, int);
void fast_sort(int num[], int, int);
void sort(int*, int*);
int main()
{
int num[10];
int i = 0;
int flag = 0;
int j = 0;
srand((unsigned int)time(NULL));
for (i = 0;i < 10; i++)
{
num[i] = rand()%30+1;
flag = i;
for (j = 0; j < flag; j++)
{
if (num[i] == num[j])
{
i--;
break;
}
}
}
puts("sort befor is :\n");
for (i = 0; i < 10; i++)
{
printf("%d\t",num[i] );
}
puts("\n");
puts("after sort is:\n");
fast_sort(&num[0], 0, 9);
for (i = 0; i < 10; i++)
{
printf("%d\t",num[i] );
}
puts("\n");
return 0;
}

int partion(int num[], int low, int higt)
{
int flag = num[low];
int pivotkey = num[low];
while(low < higt)
{
while ((low<higt)&&(num[higt]>=pivotkey))
--higt;
sort(&num[low], &num[higt]);
while ((low<higt)&&(num[low]<=pivotkey))
++low;
sort(&num[low], &num[higt]);
}
num[low] = flag;
return low;
}

void fast_sort(int num[], int low, int higt)
{
int pivot;
if (low < higt)
{
pivot = partion(num, low, higt);
fast_sort(num, low, pivot-1);
fast_sort(num, pivot+1, higt);
}
}

void sort(int *low, int *higt)
{
int tmp;
tmp = *low;
*low = *higt;
*higt = tmp;
}```
wangxiangshang | 园豆：88 (初学一级) | 2013-10-26 23:50

@xiaoleilei: js也差不多啊,只要做一些变动就就可以啊!原理还是一样!

您需要登录以后才能回答，未注册用户请先注册