Java Code for Quick Sort

In the world of computer science and programming, sorting algorithms play a crucial role in organizing and manipulating data efficiently. One such popular sorting algorithm is Quick Sort, known for its speed and effectiveness. In this article, we will explore the Java implementation of the Quick Sort algorithm, providing you with an SEO-friendly and plagiarism-free guide.

Quick Sort is a divide-and-conquer algorithm that works by selecting a pivot element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then recursively sorted, and finally combined to obtain a sorted array.

Java code for Quick Sort



import java.util.Arrays;

public class QuickSort {

    public static void quickSort(int[] array, int low, int high) {
        if (low < high) {
            int pivotIndex = partition(array, low, high);
            quickSort(array, low, pivotIndex - 1);
            quickSort(array, pivotIndex + 1, high);
        }
    }


        public static int partition ( int[] array, int low, int high){
            int pivot = array[high];
            int i = low - 1;

            for (int j = low; j < high; j++) {
                if (array[j] <= pivot) {
                    i++;
                    swap(array, i, j);
                }
            }

            swap(array, i + 1, high);
            return i + 1;
        }

        public static void swap ( int[] array, int i, int j){
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }

        public static void main (String[]args){
            int[] array = {9, 5, 1, 8, 3, 2, 7,54,3,45,24,43,23,11,33,17,67};

            System.out.println("Original Array: " + Arrays.toString(array));

            quickSort(array, 0, array.length - 1);

            System.out.println("Sorted Array: " + Arrays.toString(array));
        }
    }

quick sort in java

In the above Java code for Quick Sort, we have defined a class named QuickSort with three main methods: quickSort, partition, and swap. The quickSort method is the entry point for the Quick Sort algorithm, which recursively calls itself to sort the sub-arrays. The partition method is responsible for partitioning the array based on the pivot element. The swap method is a utility function used to swap elements in the array.

To test the Quick Sort implementation, we have a main method that creates an array of integers, performs the sorting using the quickSort method, and then prints the sorted array.

By understanding and implementing the Java code for Quick Sort, you can efficiently sort arrays of any size. Quick Sort’s average-case time complexity of O(n log n) makes it a popular choice among developers for sorting large datasets.

3 thoughts on “Java Code for Quick Sort”

Leave a Comment