算法思想:分治法
實際問題:快速排序
編寫語言:Java
Java代碼
//本篇博文代碼主要有兩種基准選擇方式:基准=低下標處的值,基准=隨機值
import java.util.Random;
public class QuickSort
{
public static void main(String[] args)
{
int[] ary = new int[] {1, 3, 4, 5, 2, 7, 0, 6, 9, 8};
System.out.print("排序前的數組:");
for(int i = 0; i < ary.length; i++)
System.out.print(ary[i] + " ");
System.out.println();
sort(ary);
System.out.print("排序后的數組:");
for(int i = 0; i < ary.length; i++)
System.out.print(ary[i] + " ");
System.out.println();
}
public static void sort(int[] a)
{
sort(a, 0, a.length - 1);
}
public static void sort(int[] a, int low, int high)
{
//當low == high時就返回
//確保數組元素為1時就停止划分,防止數組下標越界
if(low < high)
{
int pivot = randPart(a, low, high);
sort(a, low, pivot - 1);
sort(a, pivot + 1, high);
}
}
//划分尋找基准
public static int part(int[] a, int low, int high)
{
int pivot = a[low];
while(low < high)
{
//1、從右往左找比基准小的數
while(low < high && a[high] > pivot)
high--;
//a處賦值
if(low < high)
a[low] = a[high]; //此時是 a[high] < pivot, a[low] < pivot
//2、從左往右找比基准大的數
while(low < high && a[low] <= pivot)
low++;
//3、一次尋找結束,交換兩個值
//b處賦值
if(low < high)
a[high] = a[low]; //此時是 a[high] > pivot, a[low] < pivot
//a、b兩處賦值,相當於一次交換,只是分開了
}
//將pivot放到left和right相遇的地方
a[high] = pivot;
return high;
}
//划分尋找基准-隨機化優化
public static int randPart(int[] a, int low, int high)
{
Random r = new Random();
//隨機產生一個 low 到 high 的整數
int flag = low + r.nextInt(high - low + 1);
int pivot = a[flag];
//此處交換保證 1 處的賦值不出錯,
//因為只要原 a[low] < pivot,那么這個交換算法就失敗了
a[flag] = a[low];
a[low] = pivot;
while(low < high)
{
//1、從右往左找比基准小的數
while(low < high && a[high] > pivot)
high--;
if(low < high)
a[low] = a[high];
//2、從左往右找比基准大的數
while(low < high && a[low] <= pivot)
low++;
if(low < high)
a[high] = a[low];
}
//將pivot放到low和high相遇的地方
a[high] = pivot;
return high;
}
}