zoukankan      html  css  js  c++  java
  • 排序算法02----------------选择排序

    1.选择排序:首先在未排序序列中找到最小或最大元素,存放到排序序列的起始位置,再从剩余未排序元素中继续寻找最小或最大元素,然后放到已排序序列的末尾。重复第二步,直到所有元素均排序完毕

    2.选择排序和冒泡排序原理差不多,都是相邻两个元素进行比较,然后选择最大或最小的出来,但选择排序是记录最大或最小元素的下标,

    相比于冒泡排序,少了很多交换元素的操作,因此占用cpu比较少时间,速度快一些。时间复杂度:O(n²)

    3.代码如下

     1 #include<stdio.h> 
     2 void selectionSort(int * arr,int num)
     3 {
     4     int minIndex;
     5     int temp;
     6     int i,j;
     7     for(i=0;i<num;i++)
     8     {    
     9         minIndex=i;
    10         for(j=i+1;j<num;j++)
    11         {     
    12             if(arr[j]<arr[minIndex])
    13                 minIndex=j;
    14         }
    15         //找到未排序序列中的最小元素,和当前第i元素进行交换 
    16         temp=arr[i];
    17         arr[i]=arr[minIndex];
    18         arr[minIndex]=temp;
    19     }
    20 } 
    21 int main()
    22 {    
    23     int i; 
    24     int arr[10]={1,3,-9,0,10,2,8,9,19,-1};
    25     selectionSort(arr,10);//选择排序
    26     for(i=0;i<10;i++)
    27         printf("%d
    ",arr[i]);
    28     return 0;
    29 }
  • 相关阅读:
    分布式和集群
    c++ >>
    c++ ip地址相关
    c++ ip地址的操作 c版
    c++ 缺少动态库
    c++ dirname() basename()
    shell ulimit -n
    shell 进程查询相关的命令
    shell grep 高亮
    c++ swap 函数
  • 原文地址:https://www.cnblogs.com/duichoumian/p/12538917.html
Copyright © 2011-2022 走看看