简体   繁体   中英

Quick Sort not working as expected in java

I learned the theory about QuickSort. I tried to implement this algorithm in java but I am not seeing all the numbers are being sorted.I am not able to point out what mistake I am making.

QuickSort.java

public class QuickSort {

    public void quicksort(int[] arr, int lb, int ub) {
        //up=upper bound
        //lb=lower bound
        
        if(lb<ub) {
          int loc=partition(arr,lb,ub);
          quicksort(arr,lb,loc-1);
          quicksort(arr,loc+1,ub);
        }
        
    }
    
    public int partition(int[] arr,int lb,int ub) {
        int pivot=arr[lb];
        int start=lb;
        int end=ub-1;
        
        while(start<end) {
            while(arr[start]<=pivot && start<arr.length-1) {
                start++;
                }
        
        while(arr[end]>pivot) {
            end--;
        }
        
        if(start<end) {
            swap(start,end,arr);
        }
        }
        
        swap(lb,end,arr); //swapping pivot value with end
        return end;
    }
    
      public void swap(int start,int end,int[] arr) {
         // System.out.println(end+" "+pivot);
          int temp=arr[start];
          arr[start]=arr[end];
          arr[end]=temp;
      }

}

Main class:

import java.util.Arrays;

public class Program {
    
    public static void main(String[] args) {
        int[] arr= {7,6,10,5,9,2,1,15,7};
        QuickSort q=new QuickSort();
      q.quicksort(arr,0,arr.length);
      System.out.println(Arrays.toString(arr));
    }

}

My output coming is:

[2, 5, 6, 7, 1, 7, 9, 10, 15]

I rechecked my code and done some debugging but for first pass it is working fine.I dont know,at what point it is being wrong?

This dude made exactly what you are looking for :) take a look at his partition function here:

Random pivot quicksort in Java

Here is what you can do for the helper functions:

public static void sort(int arr[], int lb, int ub) {
    if (lb < ub) {

        int part = partition(arr, lb, ub);

        // Sorts the partitions
        sort(arr, lb, part - 1);
        sort(arr, part + 1, ub);
    }
}

public static void displayArray(int[] arr) {
    System.out.print("[ ");
    for (int x :
            arr) {
        System.out.print(x + " ");
    }
    System.out.print("]");
}

public static void main(String[] args) {

    int[] arr = {7, 6, 10, 5, 9, 2, 1, 15, 7};
    int len = arr.length;

    displayArray(arr);
    sort(arr, 0, len-1);
    System.out.println();
    displayArray(arr);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM