A
A
Andrey Dan2017-02-09 14:33:41
Java
Andrey Dan, 2017-02-09 14:33:41

Why doesn't quicksort work in Java?

Hello Lord! Difficulties arose when implementing the quicksort algorithm in such a way that the reference element in the Partition procedure is always the last element of the current array. Algorithm and my code is below
41a7fde7e4634c9e97b7bfab25c240e9.JPG

public static int[] quickSort(int arr[], int p, int r){
        if(p < 2){
            int q = partition(arr, p, r);
            quickSort(arr, p, q-1);
            quickSort(arr, q+1, r);
        }
        return arr;
    }

private static int partition(int[] arr, int p, int r) {
        int x = arr[r];
        int i = p-1;
        for (int j = p; j < r; j++){
            if(arr[j] < x){
                count++;
                i++;
                int temp = arr[j];
                arr[j] = arr[i];
                arr[i] = temp;
            }
            System.out.println(count);
            System.out.println(Arrays.toString(arr));
        }
        int t = arr[r];
        arr[r] = arr[i+1];
        arr[i+1] = t;

        return i+1;
    }

I suspect that the error lies in the line
int x = arr[r];
Please help me figure out where the catch lies.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Dan, 2017-02-09
@dan1sh

Lord! Allowed! Swap did it wrong. Working code below

int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;

int t = arr[i+1];
        arr[i+1] = arr[r];
        arr[r] = t;

public static int[] quickSort(int arr[], int p, int r){
        if(p < r){
            int q = partition(arr, p, r);
            quickSort(arr, p, q-1);
            quickSort(arr, q+1, r);
        }
        return arr;
    }

    private static int partition(int[] arr, int p, int r) {
        int x = arr[r];
        int i = p-1;
        for (int j = p; j < r; ++j){
            count++;
            if(arr[j] < x){

                i++;
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
            System.out.println(Arrays.toString(arr));
        }
        int t = arr[i+1];
        arr[i+1] = arr[r];
        arr[r] = t;
        return i+1;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question