黑马程序员技术交流社区
标题:
选择排序
[打印本页]
作者:
马毅
时间:
2012-12-11 00:09
标题:
选择排序
本帖最后由 Mayi 于 2012-12-12 23:09 编辑
选择排序可以说用的是蛮力,但实现比较清晰,和冒泡算法为最常用的两种排序算法
选择排序第一次迭代会扫描整个数组,找到最小的一个元素,和第一个元素交换位置,然后从第二个元素开始扫描,找到剩下元素中最小的和第二个元素交换位置,
以此类推,依次将最小的元素放在相应的位置上,
如若一个数组有N个元素,则需要执行以上过程N-1次
如若有一个int数组ary,以下代码实现了选择算法:
int temp;
for (int i = 0; i < ary.Length-1;i++ )
{
for (int j = i + 1; j < ary.Length;j++ )
{
count++;
if(ary[j] < ary[i])
{
temp = ary[j];
ary[j] = ary[i];
ary[i] = temp;
}
}
}
复制代码
以下是循环对数组操作的对照表
<strong><font color="red">|</font></strong> 5 7 6 8 9 <strong><font color="red">1</font></strong> 4 2 3
1 <strong><font color="#ff0000">|</font></strong> 5 7 6 8 9 4 <strong><font color="red">2</font></strong> 3
1 2 <strong><font color="#ff0000">|</font></strong> 5 7 6 8 9 4 <strong><font color="red">3</font></strong>
1 2 3 <strong><font color="#ff0000">|</font></strong> 5 7 6 8 9 <strong><font color="red">4</font></strong>
1 2 3 4 <strong><font color="#ff0000">|</font></strong> <strong><font color="red">5</font></strong> 7 6 8 9
1 2 3 4 5 <strong><font color="#ff0000">|</font></strong> 7 <strong><font color="red">6</font></strong> 8 9
1 2 3 4 5 6 <strong><font color="#ff0000">|</font></strong> <strong><font color="red">7</font></strong> 8 9
1 2 3 4 5 6 7 <strong><font color="#ff0000">|</font></strong> <strong><font color="red">8</font></strong> 9
1 2 3 4 5 6 7 8 <strong><font color="#ff0000">|</font></strong> <strong><font color="red">9</font></strong>
1 2 3 4 5 6 7 8 9 <strong><font color="#ff0000">|</font></strong>
复制代码
以上就是选择排序
PS:
其他算法
请看这里
作者:
马毅
时间:
2012-12-11 00:21
汗~~怎么html出来了~~~~晕~~
作者:
马毅
时间:
2012-12-11 00:30
本帖最后由 Mayi 于 2012-12-11 00:34 编辑
Mayi 发表于 2012-12-11 00:21
汗~~怎么html出来了~~~~晕~~
|
5 7 6 8 9
1
4 2 3
1
|
5 7 6 8 9 4
2
3
1 2
|
5 7 6 8 9 4
3
1 2 3
|
5 7 6 8 9
4
1 2 3 4
|
5
7 6 8 9
1 2 3 4 5
|
7
6
8 9
1 2 3 4 5 6
|
7
8 9
1 2 3 4 5 6 7
| 8
9
1 2 3 4 5 6 7 8
| 9
1 2 3 4 5 6 7 8 9
|
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2