选择排序(Selection Sort)算法也是一种比较简单的排序算法。其思路比较直观,每一步都是选择余下元素当中最小的那一个来重新排序,故而叫做选择排序算法。
其动态图如下:
算法步骤:
(1)首先从原始数组中选择最小的一个数据,将其和位于第一个位置的数据交换。
(2)接着从剩下的 n-1 个数据 中选择次小的一个数据,将其和第二个位置的数据交换。
(3)然后不断重复上述过程,直到最后两个数据完成交换。至此,便完成了对原始数组的从小到大的排序。
选择排序算法的核心代码如下:
void bubbleSort(int[] a) {
int temp;
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a.length - 1; j++) {
if (a[j] > a[j+1]) {//将相邻两个数进行比较,较大的数往后冒泡
//交换两个数字
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
选择排序算法的示例代码如下:
package cn.honda.sort;
public class BubbleSort {
static final int SIZE = 10;
public static void main(String[] args) {
int[] arr = new int[SIZE];
int i;
for (i = 0; i < SIZE; i++) {
arr[i] = (int)(100 + Math.random() * (100+1));
}
System.out.println("排序前的数组为:");
for (i = 0; i < SIZE; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
bubbleSort(arr);
System.out.println("排序后的数组为:");
for (i = 0; i < SIZE; i++) {
System.out.print(" " + arr[i]);
}
}
public static void bubbleSort(int[] a) {
int temp;
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a.length - 1; j++) {
if (a[j] > a[j+1]) {//将相邻两个数进行比较,较大的数往后冒泡
//交换两个数字
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
System.out.print("第"+i+"步排序结果:");//输出每步排序的结果
for (int k = 0; k < a.length; k++) {
System.out.print(" " + a[k]); //输出排序后的结果
}
System.out.println();
}
}
}
运行效果: