java 插入排序

	public static int[] insertSort(){
		int temp = 0;
		for (int i = 1,j=0; i < arr.length; i++) {
			temp = arr[i];
			j = i-1;
			for(;j >=0 && temp < arr[j];j--){
				arr[j+1] = arr[j];
			}
			arr[j+1] = temp;
		}
	    return arr;
	}
	
	public static int[] insertSort(int c){
		int [] t = Arrays.copyOf(arr, arr.length+1);
		int j = t.length-2;
		for(;j >=0 && c < t[j];j--){
			t[j+1] = t[j];
		}
		t[j+1] = c;
	    return t;
	}

    插入排序的规则是每一个元素和其前面的所有元素相比较,如果该元素小于前面的元素就让前面的元素后移,直到找到一个不会大于自己的元素,然后插入在该元素的后面。效率高于冒泡排序。

猜你喜欢

转载自wangning1125.iteye.com/blog/2234761