사용자가 입력 한 짧은 문자열을 Mergesort에 프로그램을 만들었습니다. 대신 무작위로 생성 된 숫자로 구성된 빈칸을 채우기를 원합니다. math.random을 사용하면 가능합니까? 또한 주어진 범위에서 숫자를 어떻게 생성합니까? (즉, 5-50 또는 0-1). 도움을 주셔서 감사합니다. 아래 코드를 포함 시켰습니다.Mergesort 숫자 배열
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);
}
}
읽고 [질문] 및 게시 "입이 가벼운 사람"을 피하십시오. 단일, 일관성있는 구체적인 질문을하십시오. – Amit
대신에 코더 입력 값을 사용합니다. 무작위로 생성 된 숫자의 목록을 원하는데, 여기서 얼마나 많은 범위를 제어 할 수 있습니다. @Amit. 임씨는이 경우 math.random이 도움이된다고 가정합니다. –
@Tomlangdorr 훨씬 좋습니다. 질문하기 만하면 질문을 편집해야합니다. (귀하의 질문과 관련이 없기 때문에 "병합 정렬"과 관련된 모든 것을 삭제하십시오.) – smarx