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

排序算法Java实现(归并排序)

时间:2015-04-25 22:39:12      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

 1 package sorting;
 2 
 3 /**
 4  * 归并排序
 5  * 平均O(nlogn),最好O(nlogn),最坏O(nlogn);空间复杂度O(n);稳定;较复杂
 6  * @author zeng
 7  *
 8  */
 9 public class GuibingPaixu {
10 
11     public static void Merge(int[] arr, int startIndex, int midIndex,
12             int endIndex) {
13         int[] tempArr = new int[arr.length];
14         System.out.println("Merge " + startIndex + "~" + endIndex);
15         int i = startIndex, j = midIndex + 1, k = startIndex;
16         while (i != midIndex + 1 && j != endIndex + 1) {
17             if (arr[i] > arr[j])
18                 tempArr[k++] = arr[i++];
19             else
20                 tempArr[k++] = arr[j++];
21         }
22         while (i != midIndex + 1)
23             tempArr[k++] = arr[i++];
24         while (j != endIndex + 1)
25             tempArr[k++] = arr[j++];
26         for (i = startIndex; i <= endIndex; i++)
27             arr[i] = tempArr[i];
28         for (int p : arr)
29             System.out.print(p + " ");
30         System.out.println();
31     }
32 
33     static void MergeSort(int[] arr, int startIndex, int endIndex) {
34         int midIndex;
35         if (startIndex < endIndex) {
36             midIndex = (startIndex + endIndex) / 2;
37             MergeSort(arr, startIndex, midIndex);// 左边有序
38             MergeSort(arr, midIndex + 1, endIndex);// 右边有序
39             Merge(arr, startIndex, midIndex, endIndex);
40         }
41     }
42 
43     public static void main(String[] args) {
44         int[] b = { 49, 38, 65, 97, 76, 13, 27, 50 };
45         MergeSort(b, 0, b.length - 1);
46         for (int i : b)
47             System.out.print(i + " ");
48 
49     }
50 }

 

排序算法Java实现(归并排序)

标签:

原文地址:http://www.cnblogs.com/zengzhihua/p/4456751.html

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