快速排序,简称快排,主要采用了“分治法”,即第一趟排序得到以某一数据为基准的序列,即该数左边的数都比该数小,右边的都比该数大(以升序考虑),然后对左序列重新找基准重复上述过程,右序列也是如此处理。
第三遍补充:http://blog.csdn.net/morewindows/article/details/6684558讲的很好。如果要记忆快速排序算法,可以采用他的挖坑填数方式来记忆。即先将数组的第一个数使用第三方变量记录下来,然后在将其视作一个空白的坑,然后开始数组前后两端的值与之前记录的值开始比较从而达到排序的目的。
代码如下:
package Sort;
public class QUICKsort
{
public static int adjust(int[] arr, int a, int b)
{
int i = a;
int j = b;
int midcount = arr[i];
//左右交换依次填充位置。
while (i < j)
{
while (i < j && midcount <= arr[j])
{
j--;
}
if (i < j)
{
arr[i] = arr[j];
i++;
}
while (i < j && midcount > arr[i])
{
i++;
}
if (i < j)
{
arr[j] = arr[i];
j--;
}
}
arr[i] = midcount;
return i;
}
public static void quickfast_sort(int[] array ,int start,int end)
{
if (start < end)
{
int i = adjust(array, start, end);//这里得到的i就是每次新序列的第一个元素在最终序列中的位置。
System.out.println(i+" ");
quickfast_sort(array, start, i-1);//左序列递归调用;
quickfast_sort(array, i+1, end);//右序列递归调用;
}
}
public static void main(String[] args) {
int[] a = { 90, 80, 70, 40, 50, 60, 60, 91, 31, 241, 145 };
quickfast_sort(a, 0, a.length-1);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
附:
上述排序时,必须先从尾部开始遍历比较,即从右端开始向左端比较,然后遇到满足的值之后跳到左端再继续重复操作。