Java Quick Sort quickSort(int[] a, int start, int end, int[] p)

Here you can find the source of quickSort(int[] a, int start, int end, int[] p)

Description

Implements a quicksort algorithm

License

BSD License

Declaration

public static void quickSort(int[] a, int start, int end, int[] p) 

Method Source Code

//package com.java2s;
/**//w ww.j  a  v a2  s.  c o  m
 * This class is part of JCodec ( www.jcodec.org ) This software is distributed
 * under FreeBSD License
 * 
 * @author Jay Codec
 * 
 */

public class Main {
    /**
     * Implements a quicksort algorithm
     */
    public static void quickSort(int[] a, int start, int end, int[] p) {
        int len = end - start;
        if (len < 2) {
            return;
        } else {
            int startPlus1 = start + 1;
            if (len == 2) {
                if (a[start] > a[startPlus1]) {
                    swap(a, start, startPlus1);
                    if (p != null)
                        swap(p, start, startPlus1);
                }
                return;
            } else if (len == 3) {
                if (a[start] > a[startPlus1]) {
                    swap(a, start, startPlus1);
                    if (p != null)
                        swap(p, start, startPlus1);
                }
                int startPlus2 = start + 2;
                if (a[startPlus1] > a[startPlus2]) {
                    swap(a, startPlus1, startPlus2);
                    if (p != null)
                        swap(p, startPlus1, startPlus2);
                }
                if (a[start] > a[startPlus1]) {
                    swap(a, start, startPlus1);
                    if (p != null)
                        swap(p, start, startPlus1);
                }
            }
        }
        int pivot = a[0];

        // partially sort
        int p_large = end - 1;
        for (int i = end - 1; i >= start; i--) {
            if (a[i] > pivot) {
                swap(a, i, p_large);
                if (p != null)
                    swap(p, i, p_large);
                p_large--;
            }
        }
        swap(a, start, p_large);
        if (p != null)
            swap(p, start, p_large);

        quickSort(a, start, p_large, p);
        quickSort(a, p_large + 1, end, p);
    }

    public static final void swap(int[] arr, int ind1, int ind2) {
        if (ind1 == ind2)
            return;
        int tmp = arr[ind1];
        arr[ind1] = arr[ind2];
        arr[ind2] = tmp;
    }
}

Related

  1. quicksort(final double[] array, final int[] index)
  2. quicksort(final long[] data, final int left, final int right)
  3. quicksort(float[] a, int[] index, int left, int right)
  4. quickSort(int[] a)
  5. quickSort(int[] a, int start, int end)
  6. quickSort(int[] arr, int left, int right)
  7. quickSort(int[] array)
  8. quicksort(int[] array)
  9. quickSort(int[] array)