How to QuickSort Array in Java


In this example, we will learn the method of quick sort in Java.

Source Code

package com.beginner.examples;

import java.util.Arrays;

public class QuickSortExample {

    public static void main(String[] args) {

        int[] arr = {10,34,235,22,1,93};

        sort(arr,0,arr.length-1);

        System.out.println(Arrays.toString(arr));

    }

    private static void sort(int[] arr,int begin,int end) {
    	
    	if(begin < end){
            int base = arr[begin];// choose base value
            int i = begin;
            int j = end;
            int mid;// record middle value
            do{
                while((arr[i] < base) && i  base)&& j > begin)// compare with base value
                {
                    j--;
                }
                if(i <= j)
                {
                    mid = arr[i];
                    arr[i] = arr[j];
                    arr[j] = mid;
                    i++;
                    j--;
                }
            }
            while(i <= j);
			if(begin  i){
			    sort(arr,i,end);// recurse
			}
        }
    }
}

Output:

[1, 10, 22, 34, 93, 235]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments