我的兄弟希望我只通過一個循環來優化我的代碼。我看不到Quicksort只能有一個循環並工作。 (他告訴我要去掉內環)用一個循環寫一個快速排序
public class QuickSort {
public static void Quick(int[] target, int lo, int hi) {
if (lo >= hi) {
return;
}
Random numberGenerator = new Random();
int pivot = numberGenerator.nextInt(hi-lo)+lo;
int pivotValue = target[pivot];
target[pivot]=target[hi];
target[hi]=pivotValue;
pivot=hi;
int counter;
for(counter=lo; counter<pivot ; counter++){
while(target[counter]>target[pivot]){
if(pivot-counter==1){
int temp=target[counter];
target[counter]=target[pivot];
target[pivot]=temp;
//return; //possibly the problem
}
else{
int temp1 = target[pivot-1];
int temp2 = target[pivot];
target[pivot]=target[counter];
target[pivot-1]=temp2;
target[counter]=temp1;
pivot=pivot-1;
}
}
}
Quick(target, lo, counter-1);
Quick(target, counter, hi);
}
public static void main(String[] args) {
int sizeOfArray = 10;
int numberOfTests = 1000;
int numFailed = 0;
for (int i = 0; i < numberOfTests; i++)
{
int[] iNeedSorting = new int[sizeOfArray];
populateArrayWithRandomNums(iNeedSorting);
//System.out.printf("Test #%d\n", i);
//System.out.printf("Original Array: %s\n", intArrayToString(iNeedSorting));
Quick(iNeedSorting, 0, iNeedSorting.length-1);
if (!isSorted(iNeedSorting)) {numFailed++;}
//System.out.printf("New Array: %s\n\n", intArrayToString(iNeedSorting));
}
System.out.printf("%d test failed\n\n", numFailed);
}
}
你的問題是你看不到內循環?它從以'while'開始的行開始。 – 2010-08-03 18:39:27
@Alex漢弗萊 - 我說我需要刪除內循環'while',以便Quicksort只能運行在1循環 – danutenshu 2010-08-03 18:40:51
'Arrays.sort(...)'由於某種原因沒有進行剪切? – 2010-08-03 18:43:41