• 十大排序算法之(三)——选择排序


    #1,选择排序简介

    选择排序(Selection sort)是一种简单直观的排序算法。它的工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。

    选择排序是不稳定的排序方法(比如序列[5, 5, 3]第一次就将第一个[5]与[3]交换,导致第一个5挪动到第二个5后面),我个人认为,按照数值来讲,这两个5没差别,所以这是不是决定这个算法不稳定还有待商榷。

    #2,c++实现算法

     1 #include<iostream>
     2 #include<vector>
     3 
     4 using namespace std;
     5 
     6 void SelectSort(vector<int> &A);
     7 void Select(vector<int> &A, int start, int stop);
     8 void swapv(int &a, int &b);
     9 
    10 int main(){
    11   vector<int> array = { 13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11 };
    12 
    13   SelectSort(array);
    14 
    15   system("Pause");
    16   return 0;
    17 }
    18 
    19 void SelectSort(vector<int> &A){
    20   int len=A.size();
    21 
    22   for (int i = 0; i < len; i++)
    23   Select(A,i,len-1);
    24 
    25 }
    26 
    27 void Select(vector<int> &A, int start, int stop){
    28   int val=A[start];
    29   int len=A.size();
    30   int pos=0;
    31 
    32   for (int i = start; i < stop + 1; i++)
    33     if(A[i]<val){
    34       pos=i;
    35       val=A[i];
    36     }
    37 
    38 
    39   if(pos!=0)
    40   swapv(A[start],A[pos]);
    41 }
    42 
    43 void swapv(int &a, int &b){
    44   a=a+b;
    45   b=a-b;
    46   a=a-b;
    47 }
    选择排序

    #3,程序实现结果

  • 相关阅读:
    用例图解析
    A B C D类网络地址
    B-树特征
    常用的中间代码
    UML图
    关于文件索引的一道习题
    数据流图的一些原则
    系统总线
    各种排序方法的时间复杂度、空间复杂度和稳定性统计表
    模拟银行自助终端系统
  • 原文地址:https://www.cnblogs.com/sophia-hxw/p/5655673.html
Copyright © 2020-2023  润新知