zoukankan      html  css  js  c++  java
  • 冒泡排序,选择排序,插入排序

    冒泡排序,使用语言python

    def bubbleSort(lists):
        count = len(lists)
        for i in range(0,count):
            for j in range(0,count-i-1):
                if lists[j]  > lists[j+1]:
                    lists[j],list[j+1] = lists[j+1],list][j]
    

      推导:

        [2,10,8,6]

        i 的范围 0~3,执行4次

        j 的范围 0~3-i-1

        第一: [2,8,6,10]

        第二: [2,6,8,10]

        第三: [2,6,8,10]

        第四: [2,6,8,10]

     1 #coding: utf-8
     2 #选择排序,使用语言python
     3 #【2,10,8,6 4 #基本思想,在待排序记录中r,r[min_index]选出最小的记录,如果r[min_index]大于r,则进行交换。
     5 def selectSort(lists):
     6     count = len(lists)
     7     for i in range(0,count):
     8         min_index = i
     9         for j in range(i+1,count):
    10             if lists[min_index] > lists[j]:
    11                 lists[min_index],lists[j] = lists[j],lists[min_index]
    12     return lists
    13 
    14 #插入排序,使用语言python
    15 #基本思想:将一个数据插入到有序的数列中,直至该数列完全有序
    16 def insertSort(lists):
    17     count = len(lists)
    18     for i in range(1,count):
    19         if lists[i-1] > lists[i]:
    20             key = lists[i]
    21             j = i - 1
    22             while j >= 0 and lists[j] > key:
    23                 lists[j+1] = lists[j]
    24                 j -= 1
    25                 lists [j + 1] = key
    26     return lists
    27 
    28 if __name__ == "__main__":
    29     #选择
    30     lists = [2,10,8,6]
    31     lists = selectSort(lists)
    32     print(lists)
    33 
    34     #插入
    35     lists = [2,10,8,6]
    36     lists = insertSort(lists)
    37     print(lists)
  • 相关阅读:
    java反射系七之动态代理
    java反射系列六之调用属性与方法
    java反射系列五之获取类的完整结构
    java反射系列四之创建运行时类的对象
    java反射系列三之类加载器
    java反射系列二
    java反射系列一
    数据类型
    类的加载、连接和初始化
    算法
  • 原文地址:https://www.cnblogs.com/jiangchenxi/p/8926595.html
Copyright © 2011-2022 走看看