数据结构-将有序数组 first[]和 second[]合并到 result[]中,result也有序,secondresult,将有序数组 first[
分享于 点击 25317 次 点评:79
数据结构-将有序数组 first[]和 second[]合并到 result[]中,result也有序,secondresult,将有序数组 first[
将有序数组 first[]和 second[]合并到 result[]中。有助于归并排序的理解
[Compare类见前面冒泡查找]
package com.algorithm.utils;/* * 将将有序数组 first[]和 second[]合并到 result[]中 * time: O(n)。 */public class Margearray<E> { public E[] marge(E first[], E second[], E[] result) { int m = first.length; int n = second.length; int copyed = 0; int copyleft = 0; int copyright = 0; Compare compare = new Compare(); while (copyleft < m && copyright < n) { if (compare.compare(first[copyleft], second[copyright]) < 0) result[copyed++] = first[copyleft++]; else result[copyed++] = second[copyright++]; } while (copyleft < m) result[copyed++] = first[copyleft++]; while (copyright < n) result[copyed++] = second[copyright++]; return result; } public static void main(String[] args) { Margearray<Integer> marge = new Margearray<Integer>(); Integer[] first = new Integer[10]; Integer[] second = new Integer[10]; for (int i = 0; i < first.length; i++) { first[i] = i; second[i] = i; } Integer[] result = new Integer[20]; result = marge.marge(first, second, result); for (Integer integer : result) { System.out.println(integer); } }}//该片段来自于http://byrx.net
用户点评