选择排序
选择排序原理:第一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在数组的起始位置;第二次再从剩余的未排序元素中寻找到最小(大)元素,然后放到已排序的序列的末尾。以此类推,直到全部待排序的数据元素的个数为1,那么就排好了。选择排序是不稳定的排序方法。
/**
* @author :Mrs.You
* @date :2020/10/18 19:07
* @description:选择排序
*/
public class SelectSort {
public static void main(String[] args) {
int[] a = {3, 2, 42, 7, 44, 23, 1};
System.out.println("排序前:" + Arrays.toString(a));
selectSort(a);
System.out.println("排序后:" + Arrays.toString(a));
}
/**
* 选择排序
* 对于规模为n的数组进行选择排序,需要进行n-1趟排序,每趟排序选出最小的数交换。(每趟只进行一次交换)
* 第1趟排序比较下标从0到n的所有数,将最小的数放在第一个(下标为0)位置;
* 第2趟排序比较下标从1到n的所有数,将最小的数放在第二个(下标为1)位置...
* 第n-1趟排序比较下标为n-1和n的所有数,将最小的数放在第n-1个(下标为n-2)位置...
* @param a
*/
public static void selectSort(int[] a) {
int index;
int temp;
for (int i = 0; i < a.length - 1; i++) {
//假定最小的数下标为i
index = i;
for (int j = i + 1; j < a.length; j++) {
if (a[index] > a[j]) {
index = j;
}
}
//如果index发生了变化才交换(如果没有改变说明假定的index就是最小值的下标,这时候交换没有意义)
if (index != i) {
System.out.print("第" + (i + 1) + "趟最小的数是a[" + index + "]=" + a[index] + "与a[" + i + "]=" + a[i] + "交换");
temp = a[index];
a[index] = a[i];
a[i] = temp;
System.out.println(",交换后:" + Arrays.toString(a));
}
}
}
}