兩個數組按大小順序排列

package com.zz.sort;

public class Compare2Arrag {
	/**
	 * 兩個數組按大小順序排列
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		//數組一和數組二必須是排序好的
		int[] oneArrags = new int[]{1,3,5,7,9};
		int[] twoArrags = new int[]{2,3,6,8};
		
		int length = oneArrags.length + twoArrags.length ;
		int left = 0;
		int rightStart = 0;
		int tempIndex = 0;
		//int middle =  oneArrags.length ;
		//int leftEnd = middle - 1;
		//int rightStart = middle;
		//int right = length -1;
		int[] tempArrags = new int[length];
		
		while (left < oneArrags.length && rightStart < twoArrags.length) {
			//比較值小的放入臨時數據
			if (oneArrags[left] < twoArrags[rightStart]) {
				tempArrags[tempIndex++] = oneArrags[left++]; 
			} else {
				tempArrags[tempIndex++] = twoArrags[rightStart++];
			}
		}
		
		//數組一沒有結束的放入臨時數組
		while(left < oneArrags.length) {
			tempArrags[tempIndex++] = oneArrags[left++]; 
		}
		
		//數組二沒有結束的放入臨時數組
		while(rightStart < twoArrags.length) {
			tempArrags[tempIndex++] = twoArrags[rightStart++];
		}
		
		for(int i = 0; i < tempArrags.length; i++ ) {
			System.out.print(tempArrags[i] + " ");
		}
	}
}

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