First, what is the insertion sort?
In fact, the insertion sort is a very simple sorting method, similar to the way we play poker, after each draw card into the original card, so that they always keep orderly.
Second, why do you want to say insert sort?
The insertion sort is an O (N2) sorting algorithm with time complexity, and it takes almost one hours to sort 1 million integers. The reason I write this blog is mainly to read the "programming Zhu Ji Nanxiong" in the Insert sort, I as a newcomer, and no main to the point.
Third, the text
First we implemented the insertion sort in the simplest way, and also with the go language I was learning recently.
Func Insertsort (arr []int) {for I: = 1; i < Len (arr); i++ { //outer loop for (j = i; j > 0 && arr[j] < arr[j-1]; j--) { //inner loop arr[j], arr[j-1] = arr[j-1], arr[j] } }}
However, some language grammar sugar or language comes with a library function is sometimes easy to use, such as some language library functions have swap () function for Exchange, but the performance is not necessarily the best.
ARR[J], arr[j-1] = arr[j-1], arr[j]
The Go language statement above actually behaves as:
TMP: = arr[j]arr[j] = arr[j-1]arr[j-1] = tmp
We find that each inner loop assigns the same initial value to TMP arr[i], so we move the TMP assignment statement out of the inner loop and into
Func Insertsort (arr []int) {for I: = 1; i < Len (arr); i++ { //outer loop tmp: = Arr[i] for (j = i; J > 0 && tmp < ARR[J-1]; j--) { //inner loop arr[j] = arr[j-1] } x[j] = tmp }}
The modified code to run on the machine is about 10% faster than before the modification, although the promotion is not big, but in the code is my new people should pay attention to the point.
(If there is an error, please correct it)
Daily learning algorithms: inserting sort