• 排序算法


    选择排序思想:

    从数组中找出第一名位置,在整体中找到最小的元素,然后与第一名交换位置,接下来在剩下的元素中,找到最小的元素,与第二名交换位置,以此类推

    时间复杂度为O^n2

    #include <iostream>
    using namespace std;
    
    template<typename T> //模板函数/泛型
    void selectionSort(T arr[],int n){
        for(int i = 0; i<n; i++){
            // 寻找[i,n)区间里的最小值
            int minIndex = i;
            for(int j=i+1 ; j < n;j++)
                if(arr[j] <arr[minIndex])
                    minIndex = j;
            swap(arr[i],arr[minIndex]);
            
        }
    }
    
    int main(){
        int a[10] = {10,9,8,7,6,5,4,3,2,1};
        selectionSort(a,10);
        for(int i=0;i<10;i++)
            cout<<a[i]<<" ";
        cout<<endl;
        return 0;
    }

    另外VScode中强烈推荐Code runner这个插件,直接右键即可自动编译输出 

  • 相关阅读:
    html 3
    html标签2
    html标签
    2017.4.27
    2017.4.26
    2017.4.25
    2017.4.20
    2017.1.18
    2017.4.17
    2017.4.16.
  • 原文地址:https://www.cnblogs.com/Erick-L/p/12573747.html
Copyright © 2020-2023  润新知