25、JAVA歸併排序

來源:互聯網
上載者:User

歸併排序時間複雜度:最好最壞平均都是nlogn空間複雜度:n穩定性:穩定的 歸併排序的用途:1、排序

  (速度僅次於快速排序,但較穩定)

2、求逆序對數【這個單獨出個筆試題,求逆序對數】

  具體思路是,在歸併的過程中計算每個小區間的逆序對數,進而計算出大區間的逆序對數(也可以用樹狀數組來求解)

 

JAVA實現歸併排序:

 

import java.util.Arrays;public class MergeSort {public static void main(String args[]){int a[] = {4,4,1,6,3};mergeSort(a,0,a.length-1);/*for(int i=0;i<a.length-1;i++)System.out.println(a[i]);*/  System.out.println(Arrays.toString(a));}private static void mergeSort(int a[],int start,int end){//int mid = (start+end)/2;//int[] temp = new int[a.length];int mid=(start&end)+((start^end)>>1);if(start<end){//跳出遞迴,原來忘記寫這一句,導致棧溢出mergeSort(a,start,mid);mergeSort(a,mid+1,end);merge(a,start,mid,mid+1,end);}}private static void merge(int a[],int start1,int end1,int start2,int end2){int i = start1;int j = start2;//int k = 0;//k與此處保持一致,System.arraycopy(temp, 0, a, start1, end2-start1+1);int k = start1;//k與此處保持一致,System.arraycopy(temp, start1, a, start1, end2-start1+1);int temp[] = new int[a.length+1];while(i<=end1 && j<=end2){if(a[i] < a[j]){temp[k++] = a[i++];//temp[k] = a[i];//i++;}else{temp[k++] = a[j++];//temp[k] = a[j];//j++;}//k++;}while(i<=end1){temp[k++] = a[i++];}while(j<=end2){temp[k++] = a[j++];}//k = start1;//for(int element:temp){//把臨時數組元素賦值給原數組//a[k++] = element;System.arraycopy(temp, start1, a, start1, end2-start1+1);}}

 

 

刪除注釋後的完整可運行代碼:

import java.util.Arrays;public class MergeSort {public static void main(String args[]){int a[] = {4,4,1,6,3};mergeSort(a,0,a.length-1);/*for(int i=0;i<a.length-1;i++)System.out.println(a[i]);*/  System.out.println(Arrays.toString(a));}private static void mergeSort(int a[],int start,int end){//int mid = (start+end)/2;int mid=(start&end)+((start^end)>>1);if(start<end){//跳出遞迴,原來忘記寫這一句,導致棧溢出mergeSort(a,start,mid);mergeSort(a,mid+1,end);merge(a,start,mid,mid+1,end);}}private static void merge(int a[],int start1,int end1,int start2,int end2){int i = start1;int j = start2;int k = start1;//k與此處保持一致,System.arraycopy(temp, start1, a, start1, end2-start1+1);int temp[] = new int[a.length+1];while(i<=end1 && j<=end2){if(a[i] < a[j]){temp[k++] = a[i++];}else{temp[k++] = a[j++];}}while(i<=end1){temp[k++] = a[i++];}while(j<=end2){temp[k++] = a[j++];}System.arraycopy(temp, start1, a, start1, end2-start1+1);//從temp數組複製到a數組}}

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.