zoukankan      html  css  js  c++  java
  • 简单的排序算法:选择排序法

    目标:将元素从小到大排列

    算法原理:遍历所有元素,选择最小的元素与第一个元素交换位置,遍历剩余元素,选择最小的元素与第二个元素交换位置,循环直道最后一个元素。

    时间复杂度:O(n^2)

    c++实现整形数组选择排序

     1 void selectSort( int arr[] , int n )
     2 {
     3     for(int i=0 ; i < n ; i++)
     4     {
     5         int minIndex=i;
     6         for(int j=i; j< n;j++)
     7         {
     8             if(arr[j]<arr[minIndex])
     9                 minIndex=j;
    10         }
    11         swap(arr[i],arr[minIndex]);
    12     }
    13     return;
    14 }

    在第一层循环内定义了辅助变量minIndex,赋值为i。swap()为交换函数,包含在名字空间std中。

    为了提高通用型,将函数改写为函数模板

     1 template <typename T>
     2 void selectSort( T arr[] , int n )
     3 {
     4     for(int i=0 ; i < n ; i++)
     5     {
     6         int minIndex=i;
     7         for(int j=i; j< n;j++)
     8         {
     9             if(arr[j]<arr[minIndex])
    10                 minIndex=j;
    11         }
    12         swap(arr[i],arr[minIndex]);
    13     }
    14     return;
    15 }

    函数模板有局限性,所以在具体使用的时候,有时需要进行运算符重载等操作

  • 相关阅读:
    大神总结的
    更改Xcode的缺省公司名
    iPhone分辨率
    iOS 的 APP 如何适应 iPhone 5s/6/6Plus 三种屏幕的尺寸?
    storyBoard(tableViewl)
    storyBoard
    XIB可视化编程
    UITableView(五)
    UITableView(四)
    UITableView(三)
  • 原文地址:https://www.cnblogs.com/Bird-of-Paradise/p/6376766.html
Copyright © 2011-2022 走看看