오빠는 하나의 루프 만 가지고 코드를 최적화하길 원합니다. 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'로 시작하는 줄에서 시작합니다. –
@Alex Humphrey - Quicksort가 1 루프에서만 실행되도록 내부 루프 'while'을 제거해야한다고 말하는 중입니다. – danutenshu
'Arrays.sort (...) '가 어떤 이유로 잘라내 지 않았습니까? –