QuickSort (qsort) Algorithm in Java

Published by Igor Khrupin on

QuickSort or qsort is the most fasters sorting algorithm. Here you can see my implementation in Java.

The recursively algorithm looks like this:

public static void qsort(int[] array, int leftIndex, int rightIndex) {
    int l = leftIndex;
    int r = rightIndex;
    int pivot = array[(leftIndex + rightIndex) >> 1];
    while (l <= r) {
        while (array[l] < pivot) {
            l++;
        }
        while (array[r] > pivot) {
            r--;
        }
        if (l <= r) {
            int temp = array[l];
            array[l] = array[r];
            array[r] = temp;
            l++;
            r--;
        }
    }
    if (leftIndex < r){
        qsort(array, leftIndex, r);
    }
    if(l < rightIndex){
        qsort(array, l, rightIndex);
    }
}

Here is visualisation:

Java source here:

Download it from github

 


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

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