歸併排序
一:歸併排序基本介紹
歸併排序是利用歸併的思想實現的排序方法,該算法採用經典的分治策略(分治法是指將問題先進行劃分,劃分成一些小問題,然後在家進行遞歸求解,而治的階段則是將分的階段得到的各答案“修補”在一起,即分而治之)。
二:規避給排序思想示意圖
歸併排序先將待排序的數組進行劃分,如圖數組[8,4,5,7,1,3,6,2],當進行完劃分之後會變成8,4,5,7,1,3,6,2單個數據。然後在進行治操作,整個過程會執行array.length-1次合併操作。
在治階段,我們需要將兩個已經有序的子序列合併成一個有序序列,比如上圖中最後一次合併,將[4,5,7,8],[1,2,3,6]兩個數組進行合併,合併成最終的 [1,2,3,4,5,6,7,8],實現步驟如下:
三:代碼
package 排序算法;
/*
歸併排序
*/
import java.text.SimpleDateFormat;
import java.util.Date;
public class MergetSort {
public static void main(String[] args) {
// int[] array = {8,4,5,7,1,3,6,2};
int[] array = new int[80000];
for (int i = 0; i < array.length; i++) {
array[i] = (int)Math.random()*80000;
}
int[] temp = new int[array.length];
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = simpleDateFormat.format(date);
System.out.println(format);
mergetSort(array,0,array.length-1,temp);
Date date1 = new Date();
String format1 = simpleDateFormat.format(date1);
System.out.println(format1);
}
//分+合
public static void mergetSort(int[] array,int left,int right,int[] temp){
if (left<right){
int mid = (left+right)/2;
//向左分解
mergetSort(array,left,mid,temp);
//向右分解
mergetSort(array,mid+1,right,temp);
//合
merge(array,left,mid,right,temp);
}
}
//治
/*
array:待排序的數組
left:數組最左邊
mid:中間數,是左邊數組的最後一個
right:右邊數組的最後一個
temp:中轉數組
*/
public static void merge(int[] array,int left,int mid,int right,int[] temp){
int i = left;
int j = mid+1;
int t = 0; //作爲temp數組的下標值
//一:比較,並將數組種的元素按照順序放到temp種
while (i<=mid&&j<=right){
if (array[i]<=array[j]){
temp[t] = array[i];
i++;
t++;
}else {
temp[t] = array[j];
j++;
t++;
}
}
//二:將左邊或者右邊剩餘的數據整體賦值到temp種
while (i<=mid){
temp[t] = array[i];
i++;
t++;
}
while (j<=right){
temp[t] = array[j];
j++;
t++;
}
//三:將數據從temp中拷貝到array中
t = 0; //將t置零
int tempLeft = left; //
while (tempLeft<=right){
array[tempLeft] = temp[t];
tempLeft++;
t++;
}
}
}
歸併排序中主要還是理解遞歸調用的思想,要能夠理解在左右劃分數據以及在什麼時候進行治的操作
劃分數據時的真正步驟: