快速排序
快速排序(Quicksort)是对冒泡排序的一种改进。
快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
基本思路
定义一个数,作为中轴数,定义两个指针,从右边开始遍历,直到找到一个比它小的数,然后从左开始遍历,找到一个比它大的数,然后交换他们,直到左指针大于右指针
Java代码实现
package com.tangbaobao.sort;
import org.junit.Test;
import java.util.Arrays;
/**
* 快速排序
*
* @author 唐学俊
* @create 2018/03/15
**/
@Test
public void fun1() {
int[] a = {6, 1, 2, 7, 9, 3, 4, 5, 10, 8};
this.quick(a, 0, a.length - 1);
System.out.println("最终结果:");
for (int i : a) {
System.out.print(i + ",");
}
}
public class QuickSort3 {
public int getMiddel(int[] arr, int low, int high) {
//设置中轴
int temp = arr[low];
while (low < high) {
//指针向左移动的条件
while (low < high && arr[high] > temp) {
high--;
}
arr[low] = arr[high];
//指针向右移动的条件
while (low < high && arr[low] < temp) {
low++;
}
arr[high] = arr[low];
}
//将中轴位置的值和碰撞到一起的值进行交换
arr[high] = temp;
//返回中轴位置
return high;
}
/**
* 快速排序方法
* @param arr
* @param low
* @param high
* @return
*/
public int[] quick(int[] arr, int low, int high) {
if (low < high) {
int mid = this.getMiddel(arr, low, high);
quick(arr, low, mid - 1);
quick(arr, mid + 1, high);
}
return arr;
}
}
时间复杂度
最坏情况:每次比较都要交换:o(n²)。
平均情况:o(nlogn)