快速排序算法Java實現
1 算法概念。
快速排序(Quicksort)是對冒泡排序的一種改進。由C. A. R. Hoare在1962年提出。
2 算法思想。
通過一趟排序將要排序的數據分割成獨立的兩部分,其中一部分的所有數據都比另外一部分的所有數據都要小,然後再按此方法對這兩部分數據分別進行快速排序,整個排序過程可以遞歸進行,以此達到整個數據變成有序序列。
3 實現思路。
①以第一個關鍵字 K 1 爲控制字,將 [K 1 ,K 2 ,…,K n ] 分成兩個子區,使左區所有關鍵字小於等於 K 1 ,右區所有關鍵字大於等於 K 1 ,最後控制字居兩個子區中間的適當位置。在子區內數據尚處於無序狀態。
②把左區作爲一個整體,用①的步驟進行處理,右區進行相同的處理。(即遞歸)
③重複第①、②步,直到左區處理完畢。
4 代碼實現(遞歸方式)
static void quicksort(int n[], int left, int right) {
int dp;
if (left < right) {
dp = partition(n, left, right);
quicksort(n, left, dp - 1);
quicksort(n, dp + 1, right);
}
}
static int partition(int n[], int left, int right) {
int pivot = n[left];
while (left < right) {
while (left < right && n[right] >= pivot)
right--;
if (left < right)
n[left++] = n[right];
while (left < right && n[left] <= pivot)
left++;
if (left < right)
n[right--] = n[left];
}
n[left] = pivot;
return left;
}
5 代碼實現(非遞歸方式)
package sort.algorithm;
import java.util.Stack;
//快速排序的非遞歸實現,利用系統的棧stack
public class QuickSortNonRecursion {
public static void main(String[] args) {
QuickSortNonRecursion qsnr = new QuickSortNonRecursion();
int[] array = {0, 2, 11, 121, 18, 99, 3, 5, 101, 22, 9, 100};
qsnr.quicksort(array);
for (int i : array) {
System.out.print(i + " ");
}
}
public void quicksort(int[] array) {
if (array == null || array.length == 1) return;
//存放開始與結束索引
Stack<Integer> s = new Stack<Integer>();
//壓棧
s.push(0);
s.push(array.length - 1);
//利用循環裏實現
while (!s.empty()) {
int right = s.pop();
int left = s.pop();
//如果最大索引小於等於左邊索引,說明結束了
if (right <= left) continue;
int i = partition(array, left, right);
if (left < i - 1) {
s.push(left);
s.push(i - 1);
}
if (i + 1 < right) {
s.push(i+1);
s.push(right);
}
}
}
//找到軸心,進行交換
public int partition (int[] data, int first, int end)
{
int temp;
int i=first,j=end;
if(first<end)
{
temp=data[i];
//當i=j的時候,則說明掃描完成了
while(i<j)
{
//從右邊向左邊掃描找到一個小於temp的元素
while(j>i&&data[j]>temp)j--;
if(i<j)
{
//將該元素賦值給temp
data[i]=data[j];
//賦值後就應該將i+1指向下一個序號
i++;
}
//然後從左邊向右邊開始掃描,找到一個大於temp的元素
while(i<j&&temp>data[i])i++;
if(i<j)
{
//將該元素賦值給temp
data[j]=data[i];
//賦值後就應該將j-1指向前一個序號
j--;
}
}
//將軸數據放在i位置中
data[i]=temp;
}
return i;
}
}