Sorting Algorithm (c) - insertion sort

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/A1344714150/article/details/88657584

Goal: Use the Insert sort of a random array of small to large sort

Thought insertion sort method: similar finishing sorting playing cards, starting from the second number, and a number of the preceding comparison, if it is smaller than, the number of exchange of two, and then compared with a front number, and so on. . . Or the current until the current number of hours greater than the number it had before the first number is the circulation was stopped, and then the next number of insertion, and repeat the process until the last performed over a number of insertion operations, the sort is complete .

Code:

    //插入排序法
	public static void insertionSort(int[] array){
		for(int i=1;i<array.length;i++){
			for(int j=i;j>0&&array[j]<array[j-1];j--){
				int temp = array[j];
				array[j] = array[j-1];
				array[j-1] = temp;
			}
		}
		
	}

carry out testing:

In the basic version of insertion sort, it is necessary to repeat the two adjacent numbers exchange operation, an exchange operation is equivalent to three times the cost assignment, it can be optimized.

Thought optimization: Use the current temporary variable e array [i] the value assigned to j is i, e, and then compare the size array [j-1] is, [j-1] If e is less than Array, then Array [j ] assigned array [j-1], the number of talk foregoing comparison continues until the ratio of e array [j-1], or a large current array [j] is the time to the first number, the cycle is stopped, the array [j ] assigned to E; then i ++, the above-described operation is repeated until the last number of the inserting operation is completed, the sort is complete.

Code:

	// 插入排序法优化
	public static void insertionSortBetter(int[] array) {
		for (int i = 1; i < array.length; i++) {
			int e = array[i];
			int j;
			for (j = i; j > 0 && e < array[j - 1]; j--) {
				array[j] = array[j - 1];
			}
			array[j] = e;
		}

	}

carry out testing:

Optimized version and basic version may be little difference in the efficiency of the usual sort, but when sorting the array tends orderly, optimized version of the sorting efficiency will rise sharply, the most extreme case (the array is completely ordered) in this case the efficiency of sorting optimized version of O (n) level.

Guess you like

Origin blog.csdn.net/A1344714150/article/details/88657584