简体   繁体   中英

trying to implement Quicksort Algorithm

Just started learning algorithms: trying to implement the quicksort algorithm with Java. But it's not showing anything in the output tried many times but unable to find the reason.
It is not showing anything.

public class Try {

    public static void main(String[] args) {
        int []arr= {22,9,8,45,28,7,1};
        int len = arr.length;
        quicksort(arr, 0, len-1); 
        for(int i = 0; i<len; i++)
            System.out.print(arr[i]+" ");
    }

    static void quicksort(int [] arr, int low, int high) {
        if (low < high) {
            int index = partition(arr, low, high);
            quicksort(arr, low, index -1);
            quicksort(arr, index+1, high);
        }
    }

    static int partition(int [] arr, int low, int high) {
        int pivot = arr[low]; 
        int i = low;
        int j = high;
        while(i<=j) {
            while(arr[i]<pivot) i++;
            while(arr[j]>pivot) j--;
        
            if(i<=j) {
                // swapping i with j 
                int temp = arr[i];  
                arr[i] = arr[j];
                arr[j] = temp;
            }
            //swapping pivot(low) with j when i<j 
            int temp = arr[low];
            arr[low] = arr[j];
            arr[j] = temp;
        }
        return j;
    }
}

Your problem comes from the partition method. You keep getting stuck in the second while loop. You should do it with a single loop, here's an exemple ( I personally prefer using a for loop ):

int pivot = arr[high];  
int i = (low - 1);  // Index of smaller element and indicates the 
                   // right position of pivot found so far

for (int j = low; j <= high- 1; j++)
{
     // If current element is smaller than the pivot
     if (arr[j] < pivot)
     {
         i++;    // increment index of smaller element
         int temp = arr[i];
         arr[i] = arr[j];
         arr[j] = temp;
     }
 }
    int temp = arr[i + 1];
    arr[i + 1] = arr[high];
    arr[high] = temp;
    return (i + 1);
    

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