归并排序
归并排序是先将待排序的数据分为左右两部分,分别对左右两部分递归,再将排序后的左右两部分归并排序
O(nlogn)
import java.util.Arrays; class Main{ static int[] nums = {2,7,8,3,1,6,9,0,5,4}; public static void mergeSort(int low,int high){ if(low<high){ int mid = (low+high)/2; mergeSort(low,mid); mergeSort(mid+1,high); merge(low,mid,high); } } public static void merge(int low,int mid,int high){ int[] temp = new int[high-low+1]; int i = low; int j = mid +1; int k = 0; while(i<=mid&&j<=high){ if(nums[i]<nums[j]) temp[k++] = nums[i++]; else temp[k++] = nums[j++]; } while(i<=mid){ temp[k++] = nums[i++]; } while(j<=high){ temp[k++] = nums[j++]; } for(int p=0;p<temp.length;p++){ nums[p+low] = temp[p]; } } public static void main(String[] args){ mergeSort(0,nums.length-1); System.out.println(Arrays.toString(nums)); } }