歸併排序 java語言實現

來源:互聯網
上載者:User

標籤:java   歸併排序   

package sort;import java.util.Random;public class MergeSort {@SuppressWarnings("unused")public boolean initTestArray(int[] testArray) {// 初始化testArrayif (testArray == null)return false;Random random = new Random();for (int i = 0; i < testArray.length; i++) {testArray[i] = random.nextInt(200);}return true;}public boolean printTestArray(int[] testArray) {// 列印testArray中的內容if (testArray == null)return false;for (int i = 0; i < testArray.length; i++) {System.out.print(testArray[i] + ",");}System.out.println();return true;}public static boolean mergeSort(int[] testArray,int left,int right){if(left<right){int mid=(left+right)/2;mergeSort(testArray,left,mid);mergeSort(testArray,mid+1,right);if(!merge(testArray,left,mid,right))return false;//for(int i=0;i<testArray.length;i++)//System.out.print(testArray[i]+",");//System.out.println();return true;}return true;}@SuppressWarnings("unused")public static boolean merge(int[] testArray,int left,int mid,int right){int i=left,j=mid+1,k=0,s=right-left+1;int[] testArray2=new int[s];if(testArray2==null){System.out.println("testArray2儲存分配失敗!");return false;}while(i<=mid&&j<=right)if (testArray[i] <= testArray[j])testArray2[k++]=testArray[i++];elsetestArray2[k++]=testArray[j++];while(i<=mid) testArray2[k++]=testArray[i++];while(j<=right) testArray2[k++]=testArray[j++];for(i=0;i<s;i++) {testArray[left+i]=testArray2[i];//System.out.print(testArray2[i]+",");}//System.out.println();return true;}public static void main(String args[]){int[] testArray = new int[20];MergeSort mergeSort=new MergeSort();mergeSort.initTestArray(testArray);System.out.println("排序前:");mergeSort.printTestArray(testArray);if(!MergeSort.mergeSort(testArray, 0, testArray.length-1)){System.out.println("排序出錯!");return;}System.out.println("排序後:");mergeSort.printTestArray(testArray);}}

著作權聲明:本文為博主原創文章,轉載請註明出處。

歸併排序 java語言實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.