最近想看了下算法,想至少對於優秀的算法有個大致的瞭解。最後發覺,快速排序是綜合來說很好的一個算法,於是記錄一下快排算法,和於其小弟冒泡排序的時間比較,讓我具體瞭解,其效率的差別,一下是代碼,和測試機率
public static void kuaipai(int a [],int low,int high){
int i, j, index;
if (low > high) {
return;
}
i = low;
j = high;
index = a[i]; // 用子表的第一個記錄做基準
while (i < j) { // 從表的兩端交替向中間掃描
while (i < j && a[j] >= index)
j--;
if (i < j)
a[i++] = a[j];// 用比基準小的記錄替換低位記錄
while (i < j && a[i] < index)
i++;
if (i < j) {// 用比基準大的記錄替換高位記錄
a[j--] = a[i];
}
}
a[i] = index;// 將基準數值替換回 a[i]
kuaipai(a, low, i - 1); // 對低子表進行遞歸排序
kuaipai(a, i + 1, high); // 對高子表進行遞歸排序
}
簡單冒泡的算法如下:
static void maopao(int[] unsorted)
{
for (int i = 0; i < unsorted.length; i++)
{
for (int j = i; j < unsorted.length; j++)
{
if (unsorted[i] > unsorted[j])
{
int temp = unsorted[i];
unsorted[i] = unsorted[j];
unsorted[j] = temp;
}
}
}
}
完整的測試如下(設置了一個按需求增加隨機數的方法,和兩個線程,同時對同樣的數組進行排序分析,看其分析時間):
package 排序;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class 快排 {
public static void main(String[] args) {
final int a[] =createarray(1000000);
final int b[] =a;
ExecutorService executorService= Executors.newFixedThreadPool(2);
for(int i =0;i<2;i++)
executorService.execute(new Runnable() {
@Override
public void run() {
Long StartTime;
if(Thread.currentThread().getName().contains("pool-1-thread-1")){
StartTime= System.currentTimeMillis();
System.out.println("快排排序 開始時間"+StartTime);
kuaipai(a,0, a.length-1);
System.out.println("快排排序 所需時間:"+(System.currentTimeMillis()-StartTime));
}else{
StartTime= System.currentTimeMillis();
System.out.println("冒泡排序 開始時間"+StartTime);
maopao(b);
System.out.println("冒泡排序 所需時間:"+(System.currentTimeMillis()-StartTime));
}
}
});
}
public static void kuaipai(int a [],int low,int high){
int i, j, index;
if (low > high) {
return;
}
i = low;
j = high;
index = a[i]; // 用子表的第一個記錄做基準
while (i < j) { // 從表的兩端交替向中間掃描
while (i < j && a[j] >= index)
j--;
if (i < j)
a[i++] = a[j];// 用比基準小的記錄替換低位記錄
while (i < j && a[i] < index)
i++;
if (i < j) // 用比基準大的記錄替換高位記錄
a[j--] = a[i];
}
a[i] = index;// 將基準數值替換回 a[i]
kuaipai(a, low, i - 1); // 對低子表進行遞歸排序
kuaipai(a, i + 1, high); // 對高子表進行遞歸排序
}
public static int[] createarray(int count){
int [] shuzu=new int[count];
for(int i=0;i<shuzu.length;i++){
shuzu[i]=(int) (Math.random()*1000);
}
return shuzu;
}
static void maopao(int[] unsorted)
{
for (int i = 0; i < unsorted.length; i++)
{
for (int j = i; j < unsorted.length; j++)
{
if (unsorted[i] > unsorted[j])
{
int temp = unsorted[i];
unsorted[i] = unsorted[j];
unsorted[j] = temp;
}
}
}
}
}
其中 測試結果如下:
當一萬條數據 一起排序時
快排排序 開始時間1496393551289
冒泡排序 開始時間1496393551289
快排排序 所需時間:6
冒泡排序 所需時間:21
當十萬條數據 一起排序時
快排排序 開始時間1496393293376
冒泡排序 開始時間1496393293376
快排排序 所需時間:37
冒泡排序 所需時間:1557
快排排序 開始時間1496393599713
冒泡排序 開始時間1496393599713
快排排序 所需時間:708
冒泡排序 所需時間:153588