zoukankan      html  css  js  c++  java
  • 选择排序-Python & Java

    选择排序:
    1、找出最小的数值放在第一位
    2、找出剩余数据中最小的数值放在第二位,以此类推,直到最后一个数值

    算法的时间复杂度为:O(n)

    '''
    选择排序:
    1、找出最小的数值放在第一位
    2、找出剩余数据中最小的数值放在第二位,以此类推,直到最后一个数值
    
    算法的时间复杂度为:O(n)
    '''
    def find_min(list):
        min = list[0]
        minIndex = 0
        for i in range(len(list)):
            if(list[i] < min):
                min = list[i]
                minIndex = i
        return minIndex
    
    def select_sort(list):
        newList = []
        for i in range(len(list)):
            minIndex = find_min(list)
            print(minIndex)
            newList.append(list.pop(minIndex))
        return newList
    
    if __name__ == '__main__':
        list = [32, 13, 28, 5, 23, 56, 12, 78, 34]
        result = select_sort(list)
        print(result)


    #第二种
    def select_sort(list):
    if len(list) < 2:
    return list
    else:
    for i in range(len(list) - 1):
    for j in range(i + 1, len(list)):
    if list[i] > list[j]:
    tmp = list[i]
    list[i] = list[j]
    list[j] = tmp
    return list

    if __name__ == "__main__":
    list = [32, 13, 28, 5, 23, 56, 12, 78, 34, 1, 5]
    result = select_sort(list)
    print(result)

     Java版:

    /**
     * 选择排序:
     1、找出最小的数值放在第一位
     2、找出剩余数据中最小的数值放在第二位,以此类推,直到最后一个数值
     * Created by fred on 2018/7/31.
     */
    public class SelectSort {
        public static void main(String[] args) {
            int[] arr = {3, 9, 1, 5, 2, 8, 4};
            selectSort(arr);
            for(int i : arr){
                System.out.println(i);
            }
        }
        public static void selectSort(int[] arr){
            for(int i = 0; i < arr.length - 1; i++){
                for(int j = i + 1; j < arr.length; j++){
                    if(arr[i] > arr[j]){
                        int tmp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = tmp;
                    }
                }
            }
        }
    }
    
  • 相关阅读:
    c++深拷贝与浅拷贝
    c++构造函数的explicit
    c++虚函数和虚函数表
    c++重载、重写、隐藏(重定义)
    c++传值、传指针、传引用
    ASP.Net Core API 学习の中间件
    WPF中String Format的用法
    ASP.Net Core API 全局处理异常
    989. Add to Array-Form of Integer
    1014. Best Sightseeing Pair
  • 原文地址:https://www.cnblogs.com/fredkeke/p/9232297.html
Copyright © 2011-2022 走看看