0
我對Java排序算法很陌生,在合併排序算法中找不到錯誤。結果不斷給我輸入數組,而不是一個排序的結果。任何幫助或建議,將不勝感激。Java合併排序錯誤?繼續獲得輸入值?
public class Mergesort {
static int [] finalarray = new int[12];
public static void main(String [] args)
{
int [] numbers = {6,10,15,4,30,60,24,90,76,100,120,140};
int [] tem = new int[12];
mergesort(numbers, tem, 0, (numbers.length - 1));
for (int i = 0; i < 12; i++)
{
System.out.println("" +finalarray[i]);
}
}
public static void mergesort(int [] num, int [] temp, int first,int last)
{
if (first < last)
{
int mid = (first + last)/2;
mergesort(num, temp, first,mid);
mergesort(num, temp, mid + 1, last);
merge(num,temp,first,mid,last);
}
}
public static void merge(int [] num, int [] temp, int firstpos, int midpos, int lastpos)
{
int half1begin = firstpos;
int half1end = midpos;
int half2begin = midpos + 1;
int half2end = lastpos;
int numbersIndex = 0;
while(half1begin <= half1end && half2begin <= half2end)
{
if (num[half1begin] <= num[half2begin])
{
temp[numbersIndex] = num[half1begin];
++half1begin;
}
else
{
temp[numbersIndex] = num[half2begin];
++half2begin;
}
numbersIndex++;
}
while(half1begin <= half1end)
{
temp[numbersIndex++] = num[half1begin++];
}
while(half2begin <= half2end)
{
temp[numbersIndex++] = num[half2begin++];
}
for (int i = 0; i < 12; i++)
{
finalarray[i] = temp[i];
}
}
}