归并排序
1.问题划分
2.递归求解
3合并问题
import java.util.Arrays; import java.util.Random; public class Main{ public static void isSort(int[] arr){ for(int i=0,j=1;j<arr.length;i++,j++){ if(arr[i]>arr[j]){ System.out.println("排序失败"); System.out.print(Arrays.toString(arr)); return; } } System.out.println("排序成功"); System.out.print(Arrays.toString(arr)); } private static void merge(int[] arr,int[] aux,int left,int mid,int right){ for(int k=left;k<=right;k++){ aux[k]=arr[k]; } int i=left; int j=mid+1; for(int k=left;k<=right;k++){ if(i>mid) arr[k]=aux[j++]; else if(j>right) arr[k]=aux[i++]; else if(aux[j]<aux[i]) arr[k]=aux[j++]; else arr[k]=aux[i++]; } } public static void sort(int[] arr,int [] aux,int left,int right){ if(left>=right) return; int mid=left+(right-left)/2; sort(arr,aux,left,mid); sort(arr,aux,mid+1,right); merge(arr,aux,left,mid,right); } public static void main(String[] args){ Random random=new Random(); int[] arr=new int[10000000]; int[] aux=new int[10000000]; for(int i=0;i<10000;i++){ arr[i]=random.nextInt(10000); } sort(arr,aux,0,arr.length-1); isSort(arr); } }
利用归并求逆序对
public static int merge_and_count(int[] arr,int[] aux,int lo,int mid,int hi){ int k=hi; int i=mid; int j=hi; int count=0; while(i>=lo&&j>mid){ if(arr[i]>arr[j]){ count+=j-mid; aux[k--]=arr[i--]; }else{ aux[k--]=arr[j--]; } } while(i>=lo){ aux[k--]=arr[i--]; } while(j>mid){ aux[k--]=arr[j--]; } for(int r=lo;r<=hi;r++){ arr[r]=aux[r]; } return count; } public static int sort(int[] arr,int aux[],int lo,int hi){ if(lo>=hi) return 0; int count=0; int mid=lo+(hi-lo)/2; count+=sort(arr,aux,lo,mid); count+=sort(arr,aux,mid+1,hi); count+=merge_and_count(arr,aux,lo,mid,hi); return count; }