gpt4 book ai didi

java - 对数字数组进行合并排序

转载 作者:行者123 更新时间:2023-12-02 03:28:31 24 4
gpt4 key购买 nike

我创建了一个程序来对用户输入的短字符串元素进行合并排序。我想用随机生成的数字填充开始数组。使用 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(max-min) + min

关于java - 对数字数组进行合并排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38426566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com