zoukankan      html  css  js  c++  java
  • 排序引论

    排序引论

    选择排序

    “一种最简单的排序算法”——《算法(第4版)》

    C++代码实现

    #include <iostream>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    //选择排序
    template<typename T>
    void selectionSort(vector<T> &v) {
    	vector<T>::iterator beg = v.begin();
    	for (vector<T>::iterator it = v.begin(); it != v.end(); it++) {
    		vector<T>::iterator e = min_element(it, v.end());
    		swap(*beg, *e);
    		beg++;
    	}
    }
    
    int main() {
    	vector<int> v = { 10, 8, 6, 4, 2, 0, 1, 3, 5, 7, 9 };
    	selectionSort(v);
    	for (auto e : v) {
    		cout << e << " ";
    	}
    }
    

    Python代码实现

    # 选择排序
    def selectionSort(l):
        for i in range(len(l)):
            scope = l[i:]
            pos = scope.index(min(scope))
            l[i],l[pos+i] = l[pos+i],l[i]
    
    if __name__ == '__main__':
        l = [10,8,6,4,2,0,1,3,5,7,9]
        selectionSort(l)
        print(l)
    

    插入排序

    “将每一张扑克牌插入到前面已经有序的牌中的适当位置”——《算法(第4版)》

    Python 代码实现

    # 插入排序
    def insertSort(l):
        for i in range(1, len(l)):
            sorting = l[:i]
            for j in range(len(l[:i])):
                if l[i] < sorting[j]:
                    l.insert(j, l.pop(i))
                    continue
    
    
    if __name__ == '__main__':
        l = [10,8,6,4,2,0,1,3,5,7,9]
        insertSort(l)
        print(l)
    
  • 相关阅读:
    取时间
    DEV控件属性
    Dev之barManager控件属性
    linq查询Contains
    绑定
    运算符转换方法组和int类型的操作数
    学习计划实践
    学习计划2
    foreacht学习
    Spring5源码分析(二) IOC 容器的初始化(五)
  • 原文地址:https://www.cnblogs.com/fengyubo/p/9721269.html
Copyright © 2011-2022 走看看