前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python go 插入排序

python go 插入排序

作者头像
用户7886150
修改2021-01-18 11:47:22
3560
修改2021-01-18 11:47:22
举报
文章被收录于专栏:bit哲学院bit哲学院

参考链接: Python中的插入排序insertion sort

插入排序 

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]

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档