빠른 키. 피벗이 중간 값일 때이 코드가 작동하도록 고심하고 있습니다. 피벗이 가장 왼쪽 값일 때 작동한다는 것을 알고 있습니다. 어떤 도움을 주시겠습니까?첫 번째 인덱스 대신 피벗이있는 퀵 정렬이 잘못 정렬됩니다.
public class Quicksort {
public static void main(String[] args) {
int[] numbers = { 1, 3, 6, 2, 2, 2, 4, 8, 4 };
System.out.println(Arrays.toString(numbers));
sort(numbers);
System.out.println(Arrays.toString(numbers));
}
public static void sort(int[] number) {
quicksort(number, 0, number.length - 1);
}
public static void quicksort(int[] array, int left, int right) {
int lowest = left, highest = right;
if (right - left >= 1) {
int pivot = array[(left + right)/2];
// works when pivot = array[left];
while (lowest < highest) {
while (array[lowest] <= pivot && lowest <= right && highest > lowest) {
lowest++;
}
while (array[highest] > pivot && highest >= left && highest >= lowest) {
highest--;
}
if (highest > lowest) {
swap(array, lowest, highest);
}
}
swap(array, left, highest); // problem area?
quicksort(array, left, highest - 1);
quicksort(array, highest + 1, right);
} else {
return;
}
}
public static void swap(int[] array, int index, int index1) {
int temp = array[index];
array[index] = array[index1];
array[index1] = temp;
}
}
이의 출력은 피터 Lawrey에 의해 제안에 따라
[1, 3, 6, 2, 2, 2, 4, 8, 4] //unsorted
[2, 2, 2, 1, 3, 4, 4, 6, 8] //wrongly "sorted"
나는 이것이 실패하고 디버거의 코드를 단계별로 실행하는 가장 간단한 예제를 제안합니다 (이것이 내가해야 할 일입니다). –
이것은 심각하게 숙제처럼 보입니다 ... 어떤 경우 든 디버깅을 통해 무엇이 있는지 찾아보십시오 잘못된. 어떤 디버거가 가장 원시적 인 방법으로 printf를 사용하는지 모른다면. – Fma
나는 문자 그대로 이것에 대해 많은 시간을 보내고 있으며 처음에는 1로 바꿀 수 없다. –