选择排序
来源:互联网 发布:mac如何重新安装系统 编辑:程序博客网 时间:2024/06/08 11:50
选择排序的描述:
1.假定一个n个长度的数组,最大值为最后一个元素。
2.最后一个元素与前n-1个元素进行比较,如果存在数比它大,更新max的值,并记录该数的下标m(为了调换)。
3.如果存在下标为m的数,调换最后一个数与该下标为m的数的位置。
4.从剩下长度为n-1的数组中选择最后一个元素为最大值,重复上述过程。
5.直到数组长度变为1,排序结束。
关于这个算法,入门级别,我一直没有好好去理解,最近自己写了一遍有点坑。。。其次算法的分析,自己在头脑中分析执行,逻辑能力绝对能锻炼好。本人觉得这个算法难的地方在于换位置,最好自己写一遍。
以下是我写的代码:
//选择排序,核心在换,将最大值放在最后一个元素位置。#include <iostream>using namespace std;void printArray(int list[],int size){ for(int i=0;i<size;i++) cout<<list[i]<<" "; cout << endl;}void selectSort(int list[],int size){ int max; int indexofmax; for(int i=size-1;i>=1;i--) { max = list[i]; indexofmax = i; for(int j=0;j<i;j++) { if(list[j]>=max) { max = list[j]; indexofmax = j; } } //存放原先假定的最大值,即最后一个元素的值。 int temp; temp = list[i]; //交换!将最大值与最后一个元素交换。 list[i] = max; list[indexofmax] = temp; }}int main(){ int testArray[13]={-1,8,3,0,78,5,14,11,10,9,77,66,88}; printArray(testArray,13); selectSort(testArray,13); printArray(testArray,13); return 0;}
0 0
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序:
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 选择排序
- 记common-email发送邮件,使用qq邮箱服务器
- linux内核之页高速缓存
- MyEclipse快捷键大全
- requestWindowFeature()隐藏标题栏无效
- javascript实现网页图片逐渐清晰
- 选择排序
- 怎样将word中的图片插入到CSDN博客中
- 服务端入门《三》(gcc 链接 静态库与动态库)
- Android 自定义倒计时的View demo 类似CountDownTimer
- 问题 A: 复杂度分析(Ⅰ)
- jquery中fadein函数实现图片逐渐清晰显示
- Android Matrix原理
- HDU2017 字符串统计
- github上传代码