【发布时间】:2013-11-29 11:46:06
【问题描述】:
这是我在快速排序算法中对列表或数组进行排序的程序,数组中间的枢轴如何随机选择枢轴?我可以使用什么算法通过快速排序(随机)对数组进行排序。
public static int a[] = {1, 3, 5, 4, 6, 2, 7};
public static void main(String[] args) {
qs(a, 0, 6);
for(int p=0;p<a.length;p++)
System.out.println("after sort" + a[p]);
}
public static void qs(int a[], int f, int l) {
int i = f;
int j = l;
int x = (l + f )/ 2;
while (i < j) {
while (a[i] < a[x])
i = i + 1;
while (a[j] > a[x])
j = j - 1;
if (i < j) {
int s = a[i];
a[i] = a[j];
a[j] = s;
i = i + 1;
j = j - 1;
}
}
if (f < j)
qs(a, f, j);
if (i < l)
qs(a, i, l);
}
public void disply(int a[])
{
for(int p=0;p<a.length;p++)
System.out.println("after sort" + a[p]);
}
【问题讨论】:
-
我删除了
C++标签,因为这显然是关于Java的 -
1) 为了尽快获得更好的帮助,请发帖 SSCCE。 2) 对代码块使用一致且符合逻辑的缩进。代码的缩进是为了帮助人们理解程序流程。
-
我不太明白你的问题。实施是否不起作用或您想要实现什么?
how can chose the pivot randomly是什么意思? AFAIK 快速排序在每个(子)数组中都有一个定义的枢轴位置。
标签: java arrays algorithm sorting