TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
问题 有一数组a,长度为n,把数组中的元素从大到小重新排列 思路 选择排序十分容易理解。可以理解为有一个盘子,里面装着很多钻石,你可以从里面拿钻石,但一次只可以拿一颗。第一次你当然会拿最大的出来了,第二次你将拿剩下的钻石中最大的。 第一趟从0到n-1中找到最大的元素,假设为a[max],把a[max]与a[0]交换,这时a[0]是最大的了。第二趟从1到n-1中找到最大的元素(a[0]已经是有序的了,我们不用再管它),把这时的最大元素a[max]与a[1]交换,如此类推。
核心代码:
static
void
sort(
int
[] array) {
int
length
=
array.length;
int
max,temp;
for
(
int
i
=
0
; i
<
length
-
1
; i
++
) {
max
=
i;
//
寻找最大元素的位置
for
(
int
j
=
i
+
1
; j
<
length; j
++
){
if
(array[j]
>
array[max]) max
=
j;
}
if
(max
!=
i){
//
交换
temp
=
array[max];
array[max]
=
array;
array
=
temp;
}
}
}
全部代码:
package
com.icescut.classic.algorithm;
public
class
SelectSort {
public
static
void
main(String[] args) {
int
[] array
=
{
10
,
-
3
,
5
,
34
,
-
34
,
5
,
0
,
9
};
//
test data
sort(array);
for
(
int
el : array) {
System.out.print(el
+
"
"
);
}
}
static
void
sort(
int
[] array) {
int
length
=
array.length;
int
max,temp;
for
(
int
i
=
0
; i
<
length
-
1
; i
++
) {
max
=
i;
//
寻找最大元素的位置
for
(
int
j
=
i
+
1
; j
<
length; j
++
){
if
(array[j]
>
array[max]) max
=
j;
}
if
(max
!=
i){
//
交换
temp
=
array[max];
array[max]
=
array;
array
=
temp;
}
}
}
}
源码下载:http://file.javaxxz.com/2014/11/13/000600859.zip |
|