zhuxin
C++博客
首页
新随笔
联系
聚合
管理
随笔-0 评论-0 文章-24 trackbacks-0
选择排序
算法描述:首先找出A中的最小元素,并将其与A[0]中的元素交换。接着。找出A中的次最小元素,并将其与A[1]中的元素进行交换。对A中头n - 1个元素继续这一过程。
1
/**/
/*
2
名称:选择排序
3
时间复杂度:O(n * n)
4
*/
5
#include
<
iostream
>
6
#include
<
time.h
>
7
#include
<
stdlib.h
>
8
using
namespace
std;
9
void
selectSort(
int
*
,
int
);
10
int
main(
void
)
11
{
12
int
n;
13
int
*
array;
14
srand(time(NULL));
/**/
/*
void srand(unsigned seed);
*/
15
while
(
true
)
16
{
17
cin
>>
n;
18
array
=
new
int
[n];
19
/**/
/*
随机生成数组
*/
20
for
(
int
i
=
0
; i
<
n;
++
i)
21
{
22
array[i]
=
rand()
%
100
;
/**/
/*
int rand(void);
*/
23
}
24
25
/**/
/*
排序前
*/
26
for
(
int
i
=
0
; i
<
n;
++
i)
27
{
28
cout
<<
array[i]
<<
'
'
;
29
}
30
cout
<<
endl;
31
32
/**/
/*
选择排序
*/
33
selectSort(array, n);
34
35
/**/
/*
排序后
*/
36
for
(
int
i
=
0
; i
<
n;
++
i)
37
{
38
cout
<<
array[i]
<<
'
'
;
39
}
40
cout
<<
endl;
41
42
delete array;
43
}
44
return
0
;
45
}
46
void
selectSort(
int
*
array,
int
length)
47
{
48
for
(
int
i
=
0
; i
<
length;
++
i)
49
{
50
int
pivot
=
i;
51
/**/
/*
从array[j .. length - 1]选择一个最小的与array[i]交换
*/
52
for
(
int
j
=
i
+
1
; j
<
length;
++
j)
53
{
54
if
(array[j]
<
array[pivot])
55
{
56
pivot
=
j;
57
}
58
}
59
/**/
/*
如果最小的不是array[i],则交换
*/
60
if
(pivot
!=
i)
61
{
62
int
temp
=
array[i];
63
array[i]
=
array[pivot];
64
array[pivot]
=
temp;
65
}
66
}
67
}
68
posted on 2012-10-22 21:04
zhuxin
阅读(79)
评论(0)
编辑
收藏
引用
所属分类:
排序算法
只有注册用户
登录
后才能发表评论。
【推荐】100%开源!大型工业跨平台软件C++源码提供,建模,组态!
相关文章:
快速排序
冒泡排序
插入排序(递归)
选择排序
归并排序
插入排序
网站导航:
博客园
IT新闻
BlogJava
博问
Chat2DB
管理
<
2025年2月
>
日
一
二
三
四
五
六
26
27
28
29
30
31
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
1
2
3
4
5
6
7
8
常用链接
我的随笔
我的评论
我参与的随笔
留言簿
给我留言
查看公开留言
查看私人留言
文章分类
C/C++(5)
Effective C++(1)
More Effective C++(1)
STL源码剖析(1)
操作系统
计算机网络
面试题(6)
排序算法(6)
设计模式
数据结构和算法(1)
数学(3)
网络编程
文章档案
2012年11月 (4)
2012年10月 (20)
搜索
最新评论