归并排序JAVA代码详解
生活随笔
收集整理的這篇文章主要介紹了
归并排序JAVA代码详解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?源代碼地址:圖解排序算法(四)之歸并排序 - dreamcatcher-cx - 博客園
我對其代碼加入了更詳細的注釋?
import java.util.Arrays;/*** @author teen* @create 2021/11/5 7:23*/ public class Test01 {public static void main(String[] args) {//定義要排序的數組int[] arr = {2,5,8,9,1,3,14,4,6,7,11,6,2,13};//定義緩存數組用來存放兩個子數組的歸并數組int[] temp = new int[arr.length];//對arr全體排序sort(arr,0,arr.length-1,temp);//打印數組System.out.println(Arrays.toString(arr));}private static void sort(int[] arr,int left,int right,int[] temp) {//如果還可以再細分(當左邊界和右邊界相同時不可再分)if(left<right){//找到兩子數組的分界(以下稱為 中間界) 中間界指向左子數組的最后一個數int mid = (left+right)/2;//先分左邊 分組為 左邊界 到 中間界//其實遞歸應該從下往上看,所以是先排右邊子數組 后排左邊子數組sort(arr,left,mid,temp);//再分右邊 分組為 中間界后一個數 到 右邊界//先對右邊子數組排序sort(arr,mid+1,right,temp);//分完后開始“治” 排序 并合并兩個子數組 以中間界為分割的兩個子數組marge(arr,left,mid,right,temp);}}//核心代碼private static void marge(int[] arr, int left, int mid, int right, int[] temp) {//確定左邊數組的第一個元素int leftIndex = left;//確定右邊數組的第一個元素int rightIndex = mid+1;//臨時數組的下標int tempIndex = 0;//現在開始比大小//左數組的第一個元素和右數組的第一個元素比較,誰大誰先加入temp 直到其中一個到達邊界while (leftIndex<=mid && rightIndex<=right){//如果左邊數組的第一個數大于右邊if (arr[leftIndex] > arr[rightIndex]){//將右子數組的第一個數放入臨時數組后 指針后移temp[tempIndex++] = arr[rightIndex++];}else {//否則將左子數組的第一個數放入臨時數組 指針后移temp[tempIndex++] = arr[leftIndex++];}}//如果左邊數組存在沒排進去的,一股腦加進去while (leftIndex<=mid){temp[tempIndex++] = arr[leftIndex++];}//如果右邊數組有剩余的,一股腦加進去while (rightIndex <=right){temp[tempIndex++] = arr[rightIndex++];}//此時temp中便保留了兩個子數組排序完成的歸并數組//先將temp數組指針歸位tempIndex = 0;//將有序歸并數組整理到原數組while (left<=right){arr[left++] = temp[tempIndex++];}} }總結
以上是生活随笔為你收集整理的归并排序JAVA代码详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 城管威逼交警“让老百姓笑话”
- 下一篇: 从html导出带样式的excel,Jqu