package com.algorithm.tiger;
/**
* @description: 快速排序
* @author: tiger
* @create: 2017-07-28 19:12
*/
public class QuickSort {
//测试
public static void main(String[] args) {
int[] arr = {12, 3, 66, 632, 343, 31, 66, 43, 664, 5, 55};
quickSort1(arr, 0, arr.length - 1);
for (int left : arr) {
System.out.print(left + " ");
}
}
public static int[] quickSort1(int[] arr, int start, int end) {
if (start > end) {
return null;
}
int left = start, right = end;
//基准数
int baseNumber = arr[left];
//翻转位
//当跑到left=right时退出
while (left != right) {
while (arr[right] >= baseNumber && left < right) right--;
while (arr[left] <= baseNumber && left < right) left++;
//交换位置
if (left < right) swap(arr, left, right);
}
//基准位归位
arr[start] = arr[left];
arr[left] = baseNumber;
//递归处理左边部分
quickSort(arr, start, left - 1);
//递归处理右边部分
quickSort(arr, left + 1, end);
return arr;
}
public static int[] quickSort(int[] arr, int start, int end) {
if (start > end) {
return null;
}
int left = start, right = end;
//基准数
int baseNumber = arr[left];
//翻转位
boolean flag = true;
//当跑到left=right时退出
while (left != right) {
if (flag) {
//如果左边大于右边,则交换。将大的调到右边
if (baseNumber > arr[right]) {
//如果满足条件,则进行数组交换
swap(arr, left, right);
flag = false;
} else {
right--;
}
} else {
if (baseNumber < arr[left]) {
swap(arr, left, right);
flag = true;
} else {
left++;
}
}
}
//flag = true
quickSort(arr, start, right - 1);
//flag = false
quickSort(arr, left + 1, end);
return arr;
}
private static void swap(int[] arr, int left, int right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
}