Home > Net >  trying to make my quick-sort program work with a while loop, ran into a hitch
trying to make my quick-sort program work with a while loop, ran into a hitch

Time:12-03

public class qsort {
    public static void main(String[] args) {
        char[] arr = {'Q', 'U', 'I', 'C', 'K', 'S', 'O', 'R', 'T', 'E', 'X', 'A', 'M', 'P', 'L', 'E'};
        System.out.println(Arrays.toString(arr));
        shuffle(arr);
        System.out.println(Arrays.toString(arr));
        System.out.println("Pivot=" arr[0]);
        int i;
        while(arr[i]<arr[j]){
            for(i=1;i<arr.length;i  ){
                if(arr[i]>arr[0]){
                    System.out.println("Left=" arr[i]);
                    break;
                }
            }
            for(int j=arr.length-1;j>i;j--){
                if(arr[j]<=arr[0]){
                    System.out.println("Right=" arr[j]);
                    exch(arr,i,j);
                    break;
                }
            }
        }
        System.out.println(Arrays.toString(arr));
        }
    public static void exch(char[] arr,int i, int j){
        char temp=arr[i];
        arr[i]=arr[j];
        arr[j]=temp;
    }
    public static void shuffle(char[] arr) {
        Random rand = new Random();
        for (int i = 0; i < arr.length; i  ) {
            int r = rand.nextInt(arr.length);
            char temp = arr[i];
            arr[i] = arr[r];
            arr[r] = temp;
        }
    }
}

CodePudding user response:

As far as i can see your problem is in the line

while(arr[i]<arr[j])

You are not initializing the variable i only creating it in this line

int i;

also the variable j is not even created thats why it cant check if the array at i is smaller than the array at j you need to think about whats the value of i and j has to be and give the variables this value

CodePudding user response:

So this is not a right algorithm for a quick sort, Quick sort has complexity of O(nlogn), your code's complexity is O(n*n). I am not sure what you mean by using while loop, you can still use while loop but you need to partition your array into two based on the pivot; a[0] in your case and then swap and that's the code which is missing from your code. While you partition the array, you check the partitioned array if its sorted or not, return the index where it agains need to partition as before and after. And you keep partiotining until the array length is 1. So revisit your algorithm.

  • Related