[算法] 插入排序,直接插入

算法水平簡直不忍直視了,笨鳥先飛,還是默默地練習吧。

插入排序算法,直接插入。

算法思路整理:

把一個序列分爲前後兩部分,前部分是已經排好序的,後部分是待排序,首先,前部分只有一個元素,肯定可以認爲是有序的,然後從後部分的數據中依次插入到前部分,插入到正確位置,遍歷完後面全部數據,完成排序。


測試源碼:

/**
 * 算法訓練
 */
package com.gopain.main;

/**
 * @author gopain 插入排序 基本思路: 將序列的第一個數作爲一個有序序列,然後從第二個開始遍歷,分別插入到有序序列中。
 */
public class InsertSort {

	public static final boolean SORT_DESC = true;
	public static final boolean SORT_ASC = false;

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		int[] datas = { 2, 3, 1, 4, 6, 12, 43, 2, 1, 2, 312, 23, 54, 65, 76,
				55, 44, 23, 55, 34, 343, 23, 321 };
		// InsertSort.sort(datas, 23, InsertSort.SORT_ASC);//排序,從0到23
		InsertSort.sort(datas, 0, 15, InsertSort.SORT_ASC);//排序從0到15
		// InsertSort.sort(datas, InsertSort.SORT_ASC);//全部排序
		for (int i = 0; i < datas.length; i++) {
			System.out.print(datas[i] + ",");
		}
	}

	/**
	 * 部分排序
	 * 
	 * @param datas
	 * @param end
	 *            結束位置
	 * @param sortDesc
	 *            是否降序
	 */
	private static void sort(int[] datas, int end, boolean sortDesc) {
		if (null == datas || end > datas.length)
			return;
		if (sortDesc)// 降序排列
			coreSortDESC(datas, 0, end);
		else
			// 升序排列
			coreSortASC(datas, 0, end);
	}

	/**
	 * 部分排序
	 * 
	 * @param datas
	 * @param begin
	 *            排序起始位置
	 * @param end
	 *            排序結束位置
	 * @param sortDesc
	 *            是否降序排列
	 */
	private static void sort(int[] datas, int begin, int end, boolean sortDesc) {
		if (null == datas || end > datas.length || 0 > begin)
			return;
		if (sortDesc)// 降序
			coreSortDESC(datas, begin, end);
		else
			// 升序
			coreSortASC(datas, begin, end);

	}

	/**
	 * 傳入需要排序處理的數據,全部排序
	 * 
	 * @param datas
	 * @param desc
	 *            是否升序排列
	 */
	private static void sort(int[] datas, final boolean desc) {
		int len = 0;
		if (null == datas || 0 == (len = datas.length))
			return;
		if (desc)// 降序排列
			coreSortDESC(datas, 0, len);
		else
			coreSortASC(datas, 0, len);
	}

	private static void coreSortASC(int[] datas, int begin, int end) {
		for (int i = begin + 1; i < end; i++) {
			if (datas[i] < datas[i - 1]) {// 如果datas[i] >
											// datas[i-1]直接插入,升序排列
				int tem = datas[i];// 提取當前值
				datas[i] = datas[i - 1];// 後移一位有序序列,爲當前值騰出一個插入的位置
				int j = i - 1;// 有序序列位置
				while (datas[j] > tem) {// 找到有序序列中tem的位置
					datas[j + 1] = datas[j];
					j--;
					if (j < 0)
						break;
				}
				datas[j + 1] = tem;// 插入當前值到有序列的位置
			}
		}
	}

	private static void coreSortDESC(int[] datas, int begin, int end) {
		for (int i = begin + 1; i < end; i++) {
			if (datas[i] > datas[i - 1]) {// 如果datas[i] >
											// datas[i-1]直接插入,降序排列
				int tem = datas[i];// 提取當前值
				datas[i] = datas[i - 1];// 後移一位有序序列,爲當前值騰出一個插入的位置
				int j = i - 1;// 有序序列位置
				while (datas[j] < tem) {// 找到有序序列中tem的位置
					datas[j + 1] = datas[j];
					j--;
					if (j < 0)
						break;
				}
				datas[j + 1] = tem;// 插入當前值到有序列的位置
			}
		}
	}

}


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