歸併排序(java機試題)

Allen-Liu發表於2017-10-07

題目要求;輸入一個陣列,以空格間隔。要求用歸併排序從小到大排序並輸出。

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++];
		}
	}
	
}


相關文章