Quicksort In-Place

  • + 0 comments

    anyone can explain why this code is wrong import java.io.; import java.util.;

    public class Solution {

    public void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
    
    public void print(int[] a) {
        for (int i : a) {
            System.out.print(i + " ");
        }
        System.out.print('\n');
    }
    
      public int partition(int[] arr, int left, int right) {
        int pivot = right;
        while (left < right) {
            while (left < right && arr[left] <= arr[pivot]) {
                left++;
            }
            while (left < right && arr[right] >= arr[pivot]) {
                right--;
            }
            swap(arr, left, right);
        }
        swap(arr, pivot, left);
        print(arr);
        return left;
    }
    
    public void quickSort(int[] a, int left, int right) {
        if (left >= right) {
            return;
        }
        int pivot = partition(a, left, right);
        quickSort(a, left, pivot - 1);
        quickSort(a, pivot + 1, right);
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = sc.nextInt();
        }
        sc.close();
        new Solution().quickSort(a, 0, a.length - 1);
    }
    

    }