How to correctly implement recursion for quicksort in java?

Member

by deron , in category: Third Party Scripts , 3 months ago

How to correctly implement recursion for quicksort in java?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 3 months ago

@deron 

Here is an example of how you can correctly implement recursion for quicksort in Java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class QuickSort {
    
    public void sort(int[] arr, int low, int high) {
        if (low < high) {
            int pivotIndex = partition(arr, low, high);
            sort(arr, low, pivotIndex - 1);
            sort(arr, pivotIndex + 1, high);
        }
    }
    
    private int partition(int[] arr, int low, int high) {
        int pivot = arr[high];
        int i = low - 1;
        
        for (int j = low; j < high; j++) {
            if (arr[j] < pivot) {
                i++;
                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;
    }
    
    public static void main(String[] args) {
        int[] arr = {29, 10, 14, 37, 13};
        QuickSort qs = new QuickSort();
        qs.sort(arr, 0, arr.length - 1);
        
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}


In this implementation, the sort method takes an array arr, and the lowest and highest indices to sort. It first checks if the low index is less than the high index, it then partitions the array using the partition method and recursively calls the sort method on the left and right sub-arrays.


The partition method selects a pivot element (usually the last element), places all elements smaller than the pivot to its left, and all larger elements to its right, and returns the index of the pivot.


The main method creates an instance of the QuickSort class, initializes an array, and calls the sort method to sort the array. Finally, it prints the sorted array.

Related Threads:

How to implement quicksort using recursion?
How to use recursion in quicksort algorithm in c?
How to implement quicksort using iterator format?
How to implement from php rawurlencode to java?
How to correctly get custom emoji on discord.js?
How to do recursion on distinct values in teradata?