快速排序

来源:互联网 发布:日本观光局数据 编辑:程序博客网 时间:2024/06/11 18:24

一直想复习下算法,先把经典的快排复习下,好好理解下分治思想:

先介绍快速排序的算法过程:

[1].记录第一个数位置和最后一个数位置; int i = low; int j = high;
[2].找到主元位置,可以是第一个数,也可以是最后一个,或者随机的一个位置,一般可以以数组中第一个位置的数,
    int povit = a[low],主元选择好了就记录不改变它的值;
[3].如果主元是第一个数,则由 j 从后向前搜索,直到找到第一个小于主元的数,与主元进行交换位置.
[4].然后由 i 从前向后搜索,找到第一个大于主元的数,并与主元交换位置.

[5].重复[3],[4]步骤,直到 i = j;



a[0] ..........a[7]
12,3,5,44,21,8,56,2


主元:a[0] = 12;
-----------------------------------------------------------------
2,3,5,44,21,8,56,12    i = 1; j = 7;

2,3,5,12,21,8,56,44    i = 3;j  =6;
---------------------- 一趟完成,开始第二趟------------------------
2,3,5,8,21,12,56,44    i = 4;j = 5;

2,3,5,8,12,21,56,44    i = 4;j = 4;
---------------------- 一趟完整移位结束,主元移到了 4 的位置------------------------

----------------------此时由主元位置分为前后2个数组-------------------------------
{2,3,5,8} 12 {21,56,44}
----------------------递归对前后2个数组进行上述移位操作---------------------------


package com.sort;


//整个过程中,不是start就是end指向pivot所存储的单元
public class Quick_Sort_Last_Demo {
// get_positon返回某一个index,在index左边的元素都比index所在元素值小,
// 右边的都比index所在元素值大
public static int get_positon(int[] a, int start, int end) {


int privot = a[start]; // 将首元素设为a[start];
while (start < end) {


while (start < end && privot <= a[end])
end--;
a[start] = a[end];// 找到第一个比
while (start < end && privot >= a[start])
start++;
a[end] = a[start];
}
a[start] = privot;


return start;


}


public static void quickSort(int[] arry, int start, int end) {
// 判断start与end的位置
if (start >= end)
return;


int pivot = get_positon(arry, start, end);


quickSort(arry, start, pivot - 1);


quickSort(arry, pivot + 1, end);


}


// 打印数组
public static void print(int arry[]) {
for (int i : arry) {
System.out.print(i + " ");
}
System.out.println();
}


public static void main(String[] args) {
int arry[] = { 5, 6, 2, 7, 1 };
int len = arry.length;


System.out.print("快速排序前数组元素为:");
print(arry);


quickSort(arry, 0, len - 1);


System.out.print("快速排序后数组元素为:");
print(arry);


}
}