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

归并排序

时间:2016-09-15 01:05:44      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

 1 package Sort;
 2 
 3 import org.junit.Test;
 4 
 5 public class MergeSort {
 6 
 7     // 归并排序
 8     public void mergeSort(int[] array) {
 9         divide(array, 0, array.length - 1);
10     }
11 
12     // 1,划分
13     public void divide(int[] array, int start, int end) {
14 
15         if (start < end) {
16             int middle = (end + start) / 2;
17             divide(array, start, middle);
18             divide(array, middle + 1, end);
19             merge(array, start, middle, end);
20         }
21     }
22 
23     // 2,归并
24     public void merge(int[] array, int start, int middle, int end) {
25 
26         // a,定义两个子数组
27         int[] left = null;
28         int[] right = null;
29         if (start > middle || middle + 1 > end)
30             return;
31         left = new int[middle - start + 1];
32         right = new int[end - middle];
33         
34         // b,对两个子数组进行赋值
35         for (int i = start; i <= middle; ++i)
36             left[i - start] = array[i];
37         for (int i = middle + 1; i <= end; ++i)
38             right[i - middle - 1] = array[i];
39 
40         // c,对两个子数组进行归并
41         int indexOfLeft = 0, indexOfRight = 0;
42         int k = start;
43         while (k <= end) {
44             if (indexOfLeft < middle - start + 1 && indexOfRight < end - middle) {
45                 if (left[indexOfLeft] < right[indexOfRight])
46                     array[k++] = left[indexOfLeft++];
47                 else
48                     array[k++] = right[indexOfRight++];
49             } else{
50                 break;
51             }
52         }
53         // 左半部分的数组已经拷贝完毕
54         if (indexOfLeft == middle - start + 1 && indexOfRight < end - middle)
55             while (indexOfRight < end - middle)
56                 array[k++] = right[indexOfRight++];
57         // 右半部分的数组已经拷贝完毕
58         if (indexOfRight == end - middle && indexOfLeft < middle - start + 1)
59             while (indexOfLeft < middle - start + 1)
60                 array[k++] = left[indexOfLeft++];
61     }
62 
63     @Test
64     public void test() {
65         int[] array = { 8, 2, 4, 9, 3, 6, 0 };
66         mergeSort(array);
67         Array.print(array);
68     }
69 }

 

归并排序

标签:

原文地址:http://www.cnblogs.com/wjf0/p/5873952.html

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