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

java归并排序

时间:2015-07-29 11:43:50      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

基本排序:归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。

技术分享

 1 public static void main(String[] args){
 2         int a[] = {34, 8, 64, 51, 32, 21};
 3         mergeSort(a, 0, a.length-1);
 4         for (int i = 0; i < a.length; i++) {
 5             System.out.print(a[i] + " ");
 6         }
 7     }
 8     
 9     public static void  mergeSort(int[] a, int left, int right) {
10         if (left < right) {
11             int center = (left+right)/2;
12             mergeSort(a, left, center);
13             mergeSort(a, center+1, right);
14             merge(a, left, center, right);
15         }
16     }
17     
18     public static void merge(int[] a, int left, int center, int right) {
19         int[] tmpArr = new int[a.length];
20         int mid = center+1;
21         int third = left;
22         int tmp = left;
23         
24         while (left <= center && mid <= right) {
25             if (a[left] <= a[mid]) {
26                 tmpArr[third++] = a[left++];
27             } else {
28                 tmpArr[third++] = a[mid++];
29             }
30         }
31         while (mid <= right) {
32             tmpArr[third++] = a[mid++];
33         }
34         while (left <= center) {
35             tmpArr[third++] = a[left++];
36         }
37         
38         while (tmp <= right) {
39             a[tmp] = tmpArr[tmp++];
40         }
41     }

 

java归并排序

标签:

原文地址:http://www.cnblogs.com/daemonspirit/p/4685176.html

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