博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
选择排序
阅读量:2513 次
发布时间:2019-05-11

本文共 2020 字,大约阅读时间需要 6 分钟。

开始慢慢复习算法,巩固基础。

从最简单的排序开始,主要是理解排序的思想,之前看了很多次书,从来没有实际过,发现结果都忘记了。

可以用扑克牌来想象排序的过程,只不过有些操作对于计算机来说要复杂一些,比如:

  • 找出队伍中的最小值一眼就看出来了,但是计算机要挨个遍历。
  • 将几找已排序的手牌向后移动,计算机需要逐个移动个体。
先记录一下
选择排序
排序思想
假设目标是从小到大。在一列无序的队伍中,首先遍历找到最小值,然后与第一个值交换位置,这样第一个值就是最小了。然后从第二个值开始遍历最小值,找到后与第二值交换位置,如此一直遍历到最后一个值。
所以需要两层循环,第一层循环用来保证遍历的次数,也就是元素的个数-1,第二层循环用来遍历得到最小值。
第0次要遍历N个数
第1次要遍历N-1个数
。。。
第n次要遍历N-n个数
如果从整理一手扑克牌的角度来看,此算法也够SB的了,因为即使是 234567891 这样的顺序,和 987654321 这样的顺序,需要的时间是一样的。
具体的代码如下:
// Defines the entry point for the console application.//#include "stdafx.h"#include "windows.h"#include "time.h"const int N = 10;int O = 0;int* GenRandom(){       srand( (unsigned)time( NULL ) );       int* a = new int[N];       for (int i = 0; i < N; i++)       {           a[i] = rand() * rand();       }       return a;}void swap(int& a, int& b){       int temp = 0;       temp = a;       a = b;       b = temp;}//small -> largevoid SelectionSort(int* ua){       //round times,遍历N次       for (int i = 0; i < N-1; i++)       {              //printf("round %d \r\n", i);              //for (int i = 0; i < N; i++)              //{              //     printf("a[%d]=%d \r\n",i, *(ua+i));              //}              int nMinIndex = i;//最小值的索引//每次确定一个值,从第一个值开始。。。第二次从第二个值开始              for (int j = i + 1; j < N; j++)              {                     if( ua[nMinIndex] >= ua[j] )                     {                           nMinIndex = j;                     }                     O++;              }              swap(ua[i], ua[nMinIndex] );       }}SYSTEMTIME StartTime = {0};FILETIME StartFileTime = {0};SYSTEMTIME EndTime= {0};FILETIME SEndFileTime= {0};int _tmain(int argc, _TCHAR* argv[]){       int* a = GenRandom();       GetSystemTime(&StartTime);       printf("timeBefore %d:%d:%d \r\n", StartTime.wMinute, StartTime.wSecond, StartTime.wMilliseconds);       SelectionSort(a);       GetSystemTime(&EndTime);       printf("timeAfter %d:%d:%d \r\n", EndTime.wMinute, EndTime.wSecond, EndTime.wMilliseconds);       printf("times %d \r\n", O);       return 0;}

转载地址:http://umlgb.baihongyu.com/

你可能感兴趣的文章
Laravel中的$loop
查看>>
CentOS7 重置root密码
查看>>
Centos安装Python3
查看>>
PHP批量插入
查看>>
laravel连接sql server 2008
查看>>
Laravel框架学习笔记之任务调度(定时任务)
查看>>
laravel 定时任务秒级执行
查看>>
浅析 Laravel 官方文档推荐的 Nginx 配置
查看>>
Swagger在Laravel项目中的使用
查看>>
Laravel 的生命周期
查看>>
CentOS Docker 安装
查看>>
Nginx
查看>>
Navicat远程连接云主机数据库
查看>>
Nginx配置文件nginx.conf中文详解(总结)
查看>>
Mysql出现Table 'performance_schema.session_status' doesn't exist
查看>>
MySQL innert join、left join、right join等理解
查看>>
sdc时序约束
查看>>
NoC片上网络
查看>>
开源SoC整理
查看>>
【2020-3-21】Mac安装Homebrew慢,解决办法
查看>>