The merge sort algorithm

Package com.ebiz.sort; 

Import java.util.Arrays; 

/ ** 
 * @author YHJ 
 * @Create 2019-09-03 22:21 
 * / ** 
 * merge sort (recursive) 
 * 
 * per phase sequence ①. o two numbers merge operation, a floor (n / 2) sequences 
 * ②. executed ① until each element has a 
* ③. compared between groups
* ④. repeat step , until all elements sorted.
* / Public class the Merge { public static void main (String [] args) { int [] ARR = {8,4,5,7,1,3,6,2,9 }; mergingSort (ARR); } public static int [] mergingSort ( int[] arr){ if(arr.length <= 1){ return arr; } int num = arr.length >> 1; int[] leftArr = Arrays.copyOfRange(arr, 0, num); int[] rightArr = Arrays.copyOfRange(arr, num, arr.length); System.out.println("split two array: " + Arrays.toString(leftArr) + " And " + Arrays.toString(rightArr)); return mergeTwoArray(mergingSort(leftArr), mergingSort(rightArr)); //不断拆分为最小单元,再排序合并 } private static int[] mergeTwoArray(int[] Of arr1, int [] arr2 is) { int I = 0, J = 0, K = 0 ; int [] = Result new new int [arr1.length arr2.length +]; // apply extra storage space after the merger an array of the while (I <arr1.length && J <arr2.length) { // select a smaller value of the two sequences into a new array IF (of arr1 [I] <= arr2 is [J]) { Result [K ++ ] of arr1 = [I ++ ]; } the else { Result [K ++] = arr2 is [J ++ ]; } } the while (I <arr1.length) { // excess sequence of elements 1 into the new array Result [K ++] = of arr1 [I ++ ]; } the while (J <arr2.length) { // sequence extra elements 2 into the new array Result [K ++] = arr2 is [J ++ ]; } System.out.println ( "section Merging : "+ of Arrays.toString (Result)); return Result; } }

 

Guess you like

Origin www.cnblogs.com/jiushixihuandaqingtian/p/11463263.html