My homework asked me to implement Quicksort algorithm exactly the same as the pseudocode in the textbook: It specifies to use HoarePartition to do the partition.
pivot <- A[leftMost]
i <- leftMost; j <- rightMost+1
and here's my code:
import java.util.Arrays;
public class Main{
public static void main(String args[]){
int[] array1 = {10, 4, 2, 8, 7, 3, 5, 9, 6, 1};
int n1 = array1.length;
System.out.print("Before sorting is: ");
System.out.println(Arrays.toString(array1));
System.out.printf("After sorting is: ");
Quicksort(array1, 0, n1 -1);
System.out.println(Arrays.toString(array1));
} //end main
public static void Quicksort(int[]array, int start, int end){
if(start<end){
int pivot = HoarePartition(array, start, end);
Quicksort(array, start, pivot-1);
Quicksort(array, pivot+1, end);
}
} //end Quicksort()
public static int HoarePartition(int[] array, int start, int end){
int pivot = array[start];
int i = start;
int j = end +1;
while(true){
while(array[i] < pivot)
i++;
do{j--}while(array[j] > pivot)
if(i <= j)
return j;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
} //end while
} //end HoarePartition()
And the output is:
Before sorting is: [10, 4, 2, 8, 7, 3, 5, 9, 6, 1]
After sorting is: [1, 3, 2, 5, 7, 4, 8, 9, 6, 10]
Apparently, it's not sorted correctly, I've been thinking over and over again but still don't know which part of my algorithm is wrong...