码迷,mamicode.com
首页 > 其他好文 > 详细

归并排序

时间:2014-07-06 21:01:33      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:art   for   代码   new   amp   ar   

它的思想是将一个无序的数组先用递归进行二分,当分解为无限小时,即为单个整数时,再对其进行排列。得出有序的数组

代码如下:

package com.jll.sort;

public class MergeSort {

    public MergeSort() {

    }

    public void merge(int[] a, int start, int finish) {
        if (start == finish)
            return;
        else {
            int mid = (start + finish) / 2;

            merge(a, start, mid);

            merge(a, mid + 1, finish);

            sort(a, start, mid+1 , finish);
        }
    }

    public void sort(int[] a, int begin, int mid, int end) {
        int middle = mid - 1;
        int low = begin;
        int high = end;
        int b[] = new int[a.length];
        int count = 0;
        while (begin <= middle && mid <= end) {
            if (a[begin] <= a[mid]){
                b[count++] = a[begin++];
            } else {
                b[count++] = a[mid++];
            }
        }

        while (begin <= middle) {
            b[count++] = a[begin++];
        }
        while (mid <= end) {
            b[count++] = a[mid++];
        }

        for (int i = low; i <= high; i++) {
            a[i] = b[i-low];
        }
    }

    public static void main(String[] args) {
        MergeSort ms = new MergeSort();
        int a[] = new int[10];
        for (int i = 0; i < 10; i++) {
            a[i] = (int) (Math.random() * 100 + 1);
        }

        System.out.println("a:");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }

        ms.merge(a, 0, 9);

        System.out.println();
        System.out.println("a:");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
    }
}

里面的代码需要仔细看才能明白其中的道理

归并排序,布布扣,bubuko.com

归并排序

标签:art   for   代码   new   amp   ar   

原文地址:http://www.cnblogs.com/lilyjia/p/3824559.html

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