快速排序:
冒泡排序的改进,每次取数组第一个元素,然后轮训整个数组,找到中间位置,每次都将数据分开两部分,再次选择基准元素的中间为止,每次都把分开的部门再次分割,分治算法的体现。
视频:http://www.tudou.com/programs/view/gtnrNh7yh6I/
Java代码实现:
package com;
public class QuickSort {
public static int getMiddle(Integer[] list, int low, int high) {
int tmp = list[low]; // 数组的第一个作为中轴
while (low < high) {
while (low < high && list[high] > tmp) {
high--;
}
list[low] = list[high]; // 比中轴小的记录移到低端
while (low < high && list[low] < tmp) {
low++;
}
list[high] = list[low]; // 比中轴大的记录移到高端
}
list[low] = tmp; // 中轴记录到尾
return low; // 返回中轴的位置
}
public static void _quickSort(Integer[] list, int low, int high) {
if (low < high) {
int middle = getMiddle(list, low, high); // 将list数组进行一分为二
_quickSort(list, low, middle - 1); // 对低字表进行递归排序
_quickSort(list, middle + 1, high); // 对高字表进行递归排序
}
}
public static void quickSort(Integer[] list) {
if (list.length > 0) {
_quickSort(list, 0, list.length - 1);
}
}
public static void main(String[] args) {
Integer[] arr = { 1, 4, 3, 5, 2 };
quickSort(arr);
for (int i : arr) {
System.out.print(i + "\t");
}
}
}