Quick Sort



Program In Java To Sort The Given Array Using Quick Sort Algorithm.

The Following Program Reads The Elements Of An Array From User And Then It Sorts The Array In Ascending Order Using Quick Sort Algorithm And Displays The Sorted Array

import java.io.*;
class QuickSort {
    void quickSort(int[] numbers, int low, int high) {
        int i = low, j = high;
        //Get The Pivot Element From The Middle Of The List
        int pivot = numbers[low + (high - low) / 2];
        int k;
        //Divide Into Two Lists
        while (i <= j) {
            //If The Current Value From The Left List Is Smaller
            //Then The Pivot Element Then Get The Next Element
            //From The Left List
            while (numbers[i] < pivot) {
                i++;
            }
            //If The Current Value From The Right List Is Larger
            //Then The Pivot Element Then Get The Next Element
            //From The Right List
            while (numbers[j] > pivot) {
                j--;
            }
            /* If We Have Found A Values In The Left List Which
             * Is Larger Then The Pivot Element And If We Have
             * Found A Value In The Right List Which Is Smaller
             * Then The Pivot Element Then We Exchange The Values
             */
            //As We Are Done We Can Increase i & j
            if (i <= j) {
                //exchange(i,j);
                k = numbers[i];
                numbers[i++] = numbers[j];
                numbers[j--] = k;
            }
        }
        if (low < j) quickSort(numbers, low, j);
        if (i < high) quickSort(numbers, i, high);
    }
    public static void main(String[] arg) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter Total Number Of Elements In An Array::");
        int t = Integer.parseInt(br.readLine());
        int[] arr = new int[t];
        for (int i = 0; i < t; i++) {
            System.out.print("\nEnter Element::");
            int e = Integer.parseInt(br.readLine());
            arr[i] = e;
        }
        //int []arr={5,4,15,16,17,3,2,1};
        QuickSort q = new QuickSort();
        q.quickSort(arr, 0, arr.length - 1);
        System.out.println("\n\nAfter Sorting Array Is::");
        for (int i = 0; i < arr.length; i++) System.out.println(arr[i]);
    }
}

OUTPUT:


Enter Total Number Of Elements In An Array::8

Enter Element::5

Enter Element::4

Enter Element::15

Enter Element::16

Enter Element::17

Enter Element::3

Enter Element::2

Enter Element::1
After Sorting Array Is::
1
2
3
4
5
15
16
17
Previous Post Next Post