我编写了以下代码,以便用Java进行快速排序:
void quicksort (int[] a, int lo, int hi)
{
// lo is the lower index, hi is the upper index
// of the region of array a that is to be sorted
int i=lo, j=hi, h;
// comparison element x
int x=a[(lo+hi)/2];
// partition
do
{
while (a[i]<x) i++;
while (a[j]>x) j--;
if (i<=j)
{
h=a[i];
a[i]=a[j];
a[j]=h;
i++;
j--;
}
} while (i<=j);
// recursion
if (lo<j) quicksort(a, lo, j);
if (i<hi) quicksort(a, i, hi);
}请回顾并可能提供一个更好的解决方案。
发布于 2011-12-17 05:37:04
一些小纸条:
swap方法:公共空交换( int[] arr,final int pos1,final int pos2) { final int temp = arrpos1;arrpos1 = arrpos2;arrpos2 =temp};发布于 2014-06-15 01:42:53
方法只能做一件事。在其他答案中,有人已经指出,例如,交换机制可以提取到自己的方法中。这一点再正确不过了,quicksort方法没有必要知道如何在数组中交换两个变量。
不要在一行中声明多个变量。它的可读性较低,而且您正在做一行多件事情。在自己的行上声明每个变量。
给变量更有意义的名称,并在最内部可能的范围内声明它们,如palacsint所示。只有一个或两个字符长的变量名作为一个规则是不好的。
请记录您的代码,特别是公共或包限制的方法。请参见以下示例:
/**
*
* @param array An array of integers that is to be sorted.
* @param lowerBound The lower index of the region of the array that is to
* be sorted.
* @param upperBound The upper index of the region of the array that is to
* be sorted.
*/
void quicksort(int[] array, int lowerBound, int upperBound) {不要依赖注释来明确代码的功能。方法应该简短,简单,只做一件事。在有意义的变量和方法名称以及良好的文档的帮助下,应该不难搞清楚该方法是干什么的。你不需要评论。
如果语句或循环中只有一行代码,有时很容易忽略括号。无论如何都要用它们。它将使您的代码长几行,但它将有助于可读性。另外,以后再给身体增加更多的线条也会更容易。
发布于 2011-12-17 09:54:07
您可以将代码缩短一点,但它可能会损害可读性:
a[i]=a[j];
a[j]=h;
i++;
j--;
//can be written as:
a[i++]=a[j];
a[j--]=h;https://codereview.stackexchange.com/questions/6939
复制相似问题