码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序

时间:2020-09-18 02:46:24      阅读:36      评论:0      收藏:0      [点我收藏+]

标签:ext   import   scanner   system   util   ring   can   next   排序   

import java.util.Scanner; public class Main { public static void sort(int [] arr,int left,int right) { if (left >= right) { return; } int m = (left + right) >>> 1; sort(arr, left, m); sort(arr, m + 1, right); int[] tmp = new int[right - left + 1]; int i = left, j = m + 1, index = 0; while (i <= m && j <= right) { if (arr[i] <= arr[j]) { tmp[index ++] = arr[i ++]; } else { tmp[index ++] = arr[j ++]; } } while (i <= m) { tmp[index ++] = arr[i ++]; } while (j <= right) { tmp[index ++] = arr[j ++]; } for (int k = left; k <= right; ++ k) { arr[k] = tmp[k - left]; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int n = in.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; ++ i) { arr[i] = in.nextInt(); } sort(arr, 0, n - 1); System.out.print(arr[0]); for (int i = 1; i < n; ++ i) { System.out.print(" " + arr[i]); } System.out.println(); } } }

归并排序

标签:ext   import   scanner   system   util   ring   can   next   排序   

原文地址:https://blog.51cto.com/tianyiya/2533739

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!