Implementing Quicksort Algorithm in Java

Quicksort is a divide and conquer algorithm. Here is an another way to implement this algorithm in Java. 

package quicksort;
import java.io.*;
public class QuickSort {
    static protected int a[];
    public static void main(String args[]) throws IOException {
        BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
        int n, low, mid, high;
        System.out.println("Enter number of elements:");
        n = Integer.parseInt(obj.readLine());
        a = new int[n];
        System.out.println("Enter elements");
        for (int i = 0; i < n; i++) {
            a[i] = Integer.parseInt(obj.readLine());
        }
        quicksort(a, 0, n - 1);
        System.out.println("Sorted List:");
        for (int j = 0; j < n; j++) {
            System.out.print(a[j] + " ");
        }
    }
    static void quicksort(int t[], int p, int r) {
        if (p < r) {
            int q = partition(t, p, r);
            quicksort(t, p, q - 1);
            quicksort(t, q + 1, r);
        }
    }
    static int partition(int ta[], int l, int h) {
        int x = ta[h];
        int i = l - 1;
        for (int j = l; j <= h - 1; j++) {
            if (ta[j] <= x) {
                i = i + 1;
                int temp = ta[j];
                ta[j] = ta[i];
                ta[i] = temp;
            }

        }
        int temp2 = ta[i + 1];
        ta[i + 1] = ta[h];
        ta[h] = temp2;
        a = ta;
        return (i + 1);
    }
}

/* OUTPUT

Enter number of elements:
6
Enter elements
15
34
26
67
95
24
Sorted List:
15 24 26 34 67 95

 */

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.