github.com/benz9527/toy-box/algo@v0.0.0-20240221120937-66c0c6bd5abd/sort/insert.go (about)

     1  package sort
     2  
     3  func InsertSort(arr []int) {
     4  	n := len(arr)
     5  	for i := 1; i < n; i++ {
     6  		edgeIdx := i - 1
     7  		if arr[edgeIdx] <= arr[i] {
     8  			continue
     9  		} else {
    10  			for j := i; j >= 1 && arr[j] < arr[j-1]; j-- {
    11  				temp := arr[j]
    12  				arr[j] = arr[j-1]
    13  				arr[j-1] = temp
    14  			}
    15  		}
    16  	}
    17  }
    18  
    19  func InsertSortSimplify(arr []int) {
    20  	n := len(arr)
    21  	for i := 1; i < n; i++ {
    22  		value := arr[i]
    23  		edgeIdx := i
    24  		for edgeIdx >= 1 && arr[edgeIdx-1] > value {
    25  			arr[edgeIdx] = arr[edgeIdx-1]
    26  			edgeIdx--
    27  		}
    28  		arr[edgeIdx] = value
    29  	}
    30  }