【Java笔试题】合并有序数组

来源:互联网 发布:淘宝澳洲运费 编辑:程序博客网 时间:2024/05/16 12:55

1、题目

将两个有序数组合并成一个有序数组。例如,arr1 = {-1,1,3},arr2 = {0,2,4},则合并后的数组为arr = {-1,0,1,2,3,4}。

2、Java代码

public class TwoArrIntoOne {    public static void main(String args[]) {        int a[] = {-113};        int b[] = {024};        int c[] = MergeList(a, b);        if (c != null)            print(c);        else            System.out.println("");    }     public static int[] MergeList(int a[], int b[]) {  //两个有序数组的合并函数        int result[];        if (checkSort(a) && checkSort(b))  //检查传入的数组是否是有序的        {            result = new int[a.length + b.length];            int i = 0, j = 0, k = 0;   //i:用于标示a数组  j:用来标示b数组  k:用来标示传入的数组            while (i < a.length && j < b.length)                if (a[i] <= b[j]) {                    result[k++] = a[i++];                } else {                    result[k++] = b[j++];                }            //以下两个while循环是用来保证两个数组比较完之后剩下的一个数组里的元素能顺利传入            while (i < a.length)                result[k++] = a[i++];            while (j < b.length)                result[k++] = b[j++];            return result;        } else {            System.out.print("非有序数组,不能进行排序!");            return null;        }    }    public static boolean checkSort(int a[]) {  //检查数组是否是顺序存储的        boolean change = true;        for (int i = 0; i < a.length - 1 && change; i++) {            for (int j = i + 1; j < a.length; j++)                if (a[j - 1] > a[j])                    return false;                else change = false;        }        return true;    }    public static void print(int b[]) {   //打印函数        for (int i = 0; i < b.length; i++) {            System.out.print(b[i] + " ");        }    }}
1 0
原创粉丝点击