數據結構--插入排序

/**
 * 插入排序,時間複雜度:O(n2)
 * @author [email protected]
 *
 */
public class InsertSort {
	
	private InsertSort(){}
	
	/**
	 * 普通插入排序
	 * @param a
	 * @param off
	 * @param len
	 */
	public static void sort(int a[], int off, int len){
		for(int i = off+1; i <= len; i++){
			if(a[i] < a[i-1]){
				//記錄值
				int temp = a[i];
				//查找位置
				int j = off;
				for(; j < i; j++){
					if(a[j] <= a[i]){
						continue;
					}else{
						break;
					}
				}
				//移動
				for(int k = i; k >= j && (k-1 >= off); k--){
					a[k] = a[k - 1];
				}
				//歸位
				a[j] = temp;
			}
			print(a);
		}
	}/*output~.~
	11,31,12,5,34,30,26,38,36,18,
	11,12,31,5,34,30,26,38,36,18,
	5,11,12,31,34,30,26,38,36,18,
	5,11,12,31,34,30,26,38,36,18,
	5,11,12,30,31,34,26,38,36,18,
	5,11,12,26,30,31,34,38,36,18,
	5,11,12,26,30,31,34,38,36,18,
	5,11,12,26,30,31,34,36,38,18,
	5,11,12,18,26,30,31,34,36,38,
	*/
	/**
	 * 帶哨兵的插入排序
	 * @param a
	 * @param off
	 * @param len
	 */
	public static void sort1(int a[], int off, int len){
		for(int i = off+1; i <= len; i++){
			if(a[i] < a[i-1]){
				//記錄值
				int temp = a[i];//哨兵
				//移動
				int k = i;
				for(; (k-1 >= off) && a[k-1] >= temp; k--){
					a[k] = a[k - 1];
				}
				//歸位
				a[k] = temp;
			}
			print(a);
		}
	} /*output~.~
	11,31,12,5,34,30,26,38,36,18,
	11,12,31,5,34,30,26,38,36,18,
	5,11,12,31,34,30,26,38,36,18,
	5,11,12,31,34,30,26,38,36,18,
	5,11,12,30,31,34,26,38,36,18,
	5,11,12,26,30,31,34,38,36,18,
	5,11,12,26,30,31,34,38,36,18,
	5,11,12,26,30,31,34,36,38,18,
	5,11,12,18,26,30,31,34,36,38,
	*/
	
	
	/**
	 * 希爾排序
	 * 現將整個待排序序列分成若干字序列,對子序列中進行直接插入排序,
	 * 整個序列基本有序的時候,再對全體序列進行一次插入排序
	 * 
	 * 關鍵是增量的確定,時間複雜度小於O(n2)
	 * 
	 * 這個示例選擇增量爲5,3,1
	 */
	
	public static void sort2(int a[], int off, int len){
		//待完善
	}
	
	public static void print(int a[]){
		for(int i : a){
			System.out.print(i+",");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		int a[] = {11, 31, 12, 5, 34, 30, 26, 38, 36, 18};
		InsertSort.sort(a, 0, a.length-1);//普通插入排序
		InsertSort.sort1(a, 0, a.length-1);//帶哨兵的插入排序
	}
}

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