数组归并排序

 

 

数组归并排序代码实现:

 

/**
 *
 */
package algorithm.sort;
import java.util.Arrays;
/**
 * A merge sort demonstration algorithm
 *
 * http://en.wikipedia.org/wiki/Merge_sort
 * http://www.itl.nist.gov/div897/sqg/dads/HTML/mergesort.html
 *
 * @author yangwm Aug 1, 2010 12:03:23 PM
 */
public class MergeSortAlgorithm {
    public static int[] mergeSort(int number[]) {
        int[] result = null;
        
        if (number.length <= 1) {
            result = number;
        } else {
            int middle = number.length / 2;
            /*
             * Partition the list into two lists and sort them recursively
             */
            int left[] = new int[middle];
            for (int i = 0; i < middle; i++) {
                left[i] = number[i];
            }
            int right[] = new int[number.length - middle];
            for (int i = 0; i < number.length - middle; i++) {
                right[i] = number[middle + i];
            }
            /*
             * Merge the two sorted lists
             */
            left = mergeSort(left);
            right = mergeSort(right);
            result = merge(left, right);
        }
        return result;
    }
    public static int[] merge(int left[], int right[]) {
        int[] result = new int[left.length + right.length];
        int leftPos = 0;
        int rightPos = 0;
        int resultPos = 0;
        while (leftPos < left.length && rightPos < right.length) {
            /* Merge sorted sublists */
            if (left[leftPos] <= right[rightPos]) {
                result[resultPos++] = left[leftPos++];
            } else {
                result[resultPos++] = right[rightPos++];
            }
        }
        if (leftPos < left.length) {
            /* append left to result */
            while (leftPos < left.length) {
                result[resultPos++] = left[leftPos++];
            }
        } else {
            /* append right to result */
            while (rightPos < right.length) {
                result[resultPos++] = right[rightPos++];
            }
        }
        return result;
    }
    public static void main(String[] args) throws Exception {
        int[] inputArray1 = { 2, 2, 4, 6, 8, 15 };
        int[] inputArray2 = { 0, 0, 1, 3, 7, 9, 10, 11 };
        int[] result = MergeSortAlgorithm.merge(inputArray1, inputArray2);
        System.out.println(Arrays.toString(result));
        int[] inputArray = { 4, 2, 1, 2, 7, 3, 9, 0, 0, 11, 10, 6, 15, 8 };
        result = MergeSortAlgorithm.mergeSort(inputArray);
        System.out.println(Arrays.toString(result));
    }
}

 

输出:

[0, 0, 1, 2, 2, 3, 4, 6, 7, 8, 9, 10, 11, 15]
[0, 0, 1, 2, 2, 3, 4, 6, 7, 8, 9, 10, 11, 15]

 

学习参考资料:

http://en.wikipedia.org/wiki/Merge_sort
http://www.itl.nist.gov/div897/sqg/dads/HTML/mergesort.html

 

 

你可能感兴趣的:(数组归并排序)