繁体   English   中英

合并数字数组

[英]Mergesort an array of numbers

我创建了一个程序来合并用户输入的一小段元素。 我想用随机生成的数字填充初始数组。 使用math.random是否可能? 另外,如何生成给定范围内的数字? (即5-50或0-1)。 感谢您的帮助,我在下面提供了我的代码。

public class MergeSort 
{
    public static void main(String[] args) 
    {
        //for (int i = 0; i < 10000; ++i)
        //{
        //  String[i] = Math.random();
        //}
        //Unsorted array
        Integer[] a = { 2, 6, 3, 5, 1, 4, 10};

        //Call merge sort
        mergeSort(a);

        //Check the output which is sorted array
        System.out.println(Arrays.toString(a));
    }

    public static Comparable[] mergeSort(Comparable[] list) 
    {
        //If list is empty; no need to do anything
        if (list.length <= 1) {
            return list;
        }

        //Split the array in half in two parts
        Comparable[] first = new Comparable[list.length / 2];
        Comparable[] second = new Comparable[list.length - first.length];
        System.arraycopy(list, 0, first, 0, first.length);
        System.arraycopy(list, first.length, second, 0, second.length);

        //Sort each half recursively
        mergeSort(first);
        mergeSort(second);

        //Merge both halves together, overwriting to original array
        merge(first, second, list);
        return list;
    }


    private static void merge(Comparable[] first, Comparable[] second, Comparable[] result) 
    {
        //Index Position in first array - starting with first element
        int iFirst = 0;

        //Index Position in second array - starting with first element
        int iSecond = 0;

        //Index Position in merged array - starting with first position
        int iMerged = 0;

        //Compare elements at iFirst and iSecond, 
        //and move smaller element at iMerged
        while (iFirst < first.length && iSecond < second.length) 
        {
            if (first[iFirst].compareTo(second[iSecond]) < 0) 
            {
                result[iMerged] = first[iFirst];
                iFirst++;
            } 
            else
            {
                result[iMerged] = second[iSecond];
                iSecond++;
            }
            iMerged++;
        }
        //copy remaining elements from both halves - each half will have already sorted elements
        System.arraycopy(first, iFirst, result, iMerged, first.length - iFirst);
        System.arraycopy(second, iSecond, result, iMerged, second.length - iSecond);
    }
}

这是构造一个充满随机整数的数组的方法。 (在这种情况下,它们是大于或等于0且小于100的随机整数。)

int[] a = new int[10];

Random rand = new Random();

for (int i = 0; i < 10; i++) {
    a[i] = rand.nextInt(100);
}

如果要生成介于5(含)和50( rand.nextInt(45) + 5 )之间的数字,则可以使用rand.nextInt(45) + 5

概括如下:

rand.nextInt(max-min) + min

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM