排序算法之歸併排序

時間複雜度:平均O(nlogn)  最好O(nlogn)  最壞O(nlogn)

空間複雜度:O(n)

穩定性:穩定

特點:n大時較好

public class MergeSort {

	public static void main(String[] args) {
		int[] arr = { 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 };
		sort(arr, 0, arr.length - 1);
		System.out.println(Arrays.toString(arr));
	}

	public static void sort(int[] arr, int low, int high) {
		int mid = (low + high) >> 1;
		if (low < high) {
			// 左邊
			sort(arr, low, mid);
			// 右邊
			sort(arr, mid + 1, high);
			// 左右歸併
			merge(arr, low, mid, high);
		}
	}

	public static void merge(int[] arr, int low, int mid, int high) {
		int[] temp = new int[high - low + 1];
		int i = low;// 左指針
		int j = mid + 1;// 右指針
		int k = 0;
		// 把較小的數先移到新數組中
		while (i <= mid && j <= high) {
			if (arr[i] < arr[j]) {
				temp[k++] = arr[i++];
			} else {
				temp[k++] = arr[j++];
			}
		}
		// 把左邊剩餘的數移入數組
		while (i <= mid) {
			temp[k++] = arr[i++];
		}
		// 把右邊邊剩餘的數移入數組
		while (j <= high) {
			temp[k++] = arr[j++];
		}
		// 把新數組中的數覆蓋arr數組
		for (int k2 = 0; k2 < temp.length; k2++) {
			arr[k2 + low] = temp[k2];
		}
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章