集計ソート(java機試験問題)
テーマの要件スペース間隔で配列を入力します.集計ソートで小さいから大きいまでソートして出力する必要があります.
JAvaは次のように実装されています.
JAvaは次のように実装されています.
import java.util.Scanner;
public class MergeSort
{
/**
*
*/
public static void main(String[] args)
{
Scanner str = new Scanner(System.in);
String[] strlist = str.nextLine().split(" ");// ,
int[] list = new int[strlist.length];// java ,
for (int i = 0; i < strlist.length; i++)
{
list[i] = Integer.parseInt(strlist[i]);
}
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i] + " ");
}
System.out.println();
//bubbleSort(list);//
//insertSort(list);
//selectSort(list);
mergeSort(list);
for (int e : list)
{
System.out.print(e + " ");
}
}
// ,
public static void mergeSort(int[] list)
{
if (list.length > 1)
{
//
int[] firstHalf = new int[list.length / 2];
System.arraycopy(list, 0, firstHalf, 0, list.length / 2);//
mergeSort(firstHalf);
//
int[] secondHalf = new int[list.length - list.length / 2];
System.arraycopy(list, list.length / 2, secondHalf, 0, list.length - list.length / 2);
mergeSort(secondHalf);
//
merge(firstHalf, secondHalf, list);
}
}
// ,
public static void merge(int[] list1, int[] list2, int[] list)
{
int current1 = 0, current2 = 0, current3 = 0;//
while (current1 < list1.length && current2 < list2.length)
{
if (list1[current1] < list2[current2])
{
list[current3++] = list1[current1++];
}
else
{
list[current3++] = list2[current2++];
}
}
while (current1 < list1.length)
{
list[current3++] = list1[current1++];
}
while (current2 < list2.length)
{
list[current3++] = list2[current2++];
}
}
}