python go 插入排序

插入排序

1. 插入排序

2. code

python

# -*- coding: utf-8 -*-

class InsertionSort:

    def __init__(self, c_list):
        assert isinstance(aim_list, list)
        self.c_list = c_list
        self.sorted()

    def sorted(self):
        for i in range(1, len(self.c_list)):
            j_std = self.c_list[i]
            j = i - 1
            while j > 0 and self.c_list[j] > j_std:
                self.c_list[j + 1] = self.c_list[j]
                j-=1
            self.c_list[j+1] = j_std
        print("insertion-sort: ", self.c_list)


if __name__ == "__main__":
    aim_list = [8,1,5,3,7,3,2,9]
    insertion_sort = InsertionSort(aim_list)
    
    # 输出结果:
    # insertion-sort:  [8, 1, 2, 3, 3, 5, 7, 9]

go

package main

import (
	"fmt"
)

func main() {
	fmt.Println("Let`s start going...")
	slice := []int{3, 7, 8, 1, 4, 2, 8, 0, 4}
	fmt.Println("Base slice: ", slice)
	newSlice := insertionSort(slice)
	fmt.Println("Sort slice: ", newSlice)
}

// insertionSort 接受一个切片并对其排序
// 返回一个排序之后的切片
func insertionSort(slice []int) (slice1 []int) {
	for i := 1; len(slice) > i; i++ {
		key := slice[i]
		j := i - 1
		for j >= 0 && slice[j] > key {
			slice[j+1] = slice[j]
			j--
		}
		slice[j+1] = key
	}
	return slice
}


// 输出结果:
// Base slice:  [3 7 8 1 4 2 8 0 4]
// Sort slice:  [0 1 2 3 4 4 7 8 8]

猜你喜欢

转载自blog.csdn.net/qq_40601372/article/details/101302447
今日推荐