데이터 구조 -- 삽입 정렬

2155 단어
/**
 *     ,     :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);//        
	}
}

좋은 웹페이지 즐겨찾기