/**
* 选择排序
* @author owen_liu
*
*/
public class ChoiceSort {
public static void main(String[] args) {
int a[] = {23, 38, 65, 33, 44, 13, 27, 49, 33, 34, 12, 64, 5, 4, 62};
// sort(a);
_choiceSort(a);
// for (int i = 0; i < a.length; i++) {
// System.out.print(a[i] + ",");
// }
}
/**
* 选择排序
* @param a
*/
public static void sort(int[] a) {
int temp = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
//打印效果输出
for (int k = 0; k < a.length; k++) {
System.out.print(a[k] + " ");
}
System.out.println();
}
}
/**
* 选择排序(优化)
* @param a
*/
public static void _choiceSort(int[] a) {
if (a == null || a.length <= 0) {
return;
}
int min = 0;
int tmp = 0;
for (int i = 0; i < a.length; i++) {
min = i; /* 将当前下标定义为最小值下标 */
for (int j = i + 1; j < a.length; j++) {
if (a[min] > a[j]) { /* 如果有小于当前最小值的关键字 */
min = j; /* 将此关键字的下标赋值给min */
}
}
if (i != min) {/* 若min不等于i,说明找到最小值,交换 */
tmp = a[min];
a[min] = a[i];
a[i] = tmp;
}
//打印效果输出
for (int k = 0; k < a.length; k++) {
System.out.print(a[k] + " ");
}
System.out.println();
}
}
}
程序运行效果:
4 38 65 33 44 13 27 49 33 34 12 64 5 23 62
4 5 65 33 44 13 27 49 33 34 12 64 38 23 62
4 5 12 33 44 13 27 49 33 34 65 64 38 23 62
4 5 12 13 44 33 27 49 33 34 65 64 38 23 62
4 5 12 13 23 33 27 49 33 34 65 64 38 44 62
4 5 12 13 23 27 33 49 33 34 65 64 38 44 62
4 5 12 13 23 27 33 49 33 34 65 64 38 44 62
4 5 12 13 23 27 33 33 49 34 65 64 38 44 62
4 5 12 13 23 27 33 33 34 49 65 64 38 44 62
4 5 12 13 23 27 33 33 34 38 65 64 49 44 62
4 5 12 13 23 27 33 33 34 38 44 64 49 65 62
4 5 12 13 23 27 33 33 34 38 44 49 64 65 62
4 5 12 13 23 27 33 33 34 38 44 49 62 65 64
4 5 12 13 23 27 33 33 34 38 44 49 62 64 65
4 5 12 13 23 27 33 33 34 38 44 49 62 64 65