Java教程

八大排序归并排序

本文主要是介绍八大排序归并排序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
public class MergeSort {
      public static void main(String[] args) {
    	  int[] arr = new int[]{2,5,6,4,8,5,4,1,22,3,45};
    	  merge(arr,0,arr.length-1);
    	  System.out.println(Arrays.toString(arr));
      }
      
      
      public static void merge(int arr[],int left,int right) {
    	  
    	  if(left ==right) {
    		  return;
    	  }
    	  int mid = (left +right) / 2;
    	  merge(arr,left,mid);
    	  merge(arr,mid+1,right);
    	  
    	  he(arr,left,mid,right);
    	  
      }
      
      public static void he(int[] arr,int left,int mid,int right) {
    	  int s1=left;
    	  int s2 = mid+1;
    	  int index=0;
    	  int temp[] = new int[right-left+1];
    			  while(s1<=mid&&s2<=right) {
    				  if(arr[s1]<=arr[s2]) {
    					  temp[index]=arr[s1];
    					  s1++;
    					  index++;
    				  }
    				  else {
    					  temp[index] = arr[s2];
    					  s2++;
    					  index++;
    				  }
    			  }
    			  while(s1<=mid) {
    				  temp[index] = arr[s1];
    				  index++;
    				  s1++;
    			  }
    			  
    			  while(s2<=right) {
    				  temp[index] = arr[s2];
    				  index++;
    				  s2++;
    			  }
    			  
    			  for(int i = 0;i<temp.length;i++) {
    				  arr[i+left] = temp[i];
    			  }
    				  
      }
}

采用了分治思想

这篇关于八大排序归并排序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!