package com.datastack.sort;

import java.util.Arrays;

public class QickSort {

    public static void main(String[] args) {

        int[] t = new int[] { 2, 3, 6, -2, 7, 3, 8, 86, -4, 3, -82, 8 };

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

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

    }

    public static void exchange(int left, int right, int[] array) {

        int t = array[left];

        array[left] = array[right];

        array[right] = t;

    }

    public static void sort(int start, int end, int[] array) {

        if (start >= end)

            return;

        int right = end, left = start;

        int referenceNumber = array[left];

        boolean leftGo = false;

        left++;

        for (; right > left;) {

            if (array[right] < referenceNumber && array[left] > referenceNumber) {

                exchange(left, right, array);

                leftGo = false;

            }

            if (!leftGo) {

                if (array[right] < referenceNumber)

                    leftGo = true;

                else

                    right--;

            }

            if (leftGo) {

                if (array[left] > referenceNumber)

                    leftGo = false;

                else

                    left++;

            }

        }

        exchange(start, left, array);

        sort(start, left - 1, array);

        sort(left + 1, end, array);

    }

}