public class caogao {
//选择排序
private static void selectSort(int[] arr) {
for(int i=0;i<arr.length-1;i++){ //外层循环为找最小值的趟数
//将无序区的第一个元素的索引赋值给 min
int minIndex = i;
//minIndex 保存了最小值的索引
for(int j=i+1;j<arr.length;j++){//内层循环单趟找最小
if(arr[j] < arr[minIndex])
minIndex = j;
}
if(minIndex != i){
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
}
//插入排序
private static void insertSort(int[] array) {
//i 用来代表无序区的第一个元素的索引
for(int i = 1;i<array.length;i++){
//先备份待插入的元素,移动的过程中,该位置的值会被修改。
int temp = array[i];
//用来将有序区中 比 无序区的第一个元素大的元素,整体右移一位。
int j = 0;
for(j=i-1;j>=0 && array[j] >temp ;j--){
array[j+1] = array[j];
}
//将 temp 插入到空白位置
array[j+1] = temp;
}
}
public static void main(String[] args) {
int i[]= {2,4,2,5,1};
insertSort(i);
for (int j : i) {
System.out.print(j);
}
// selectSort(i);
/* for (int j : i) {
System.out.print(j);
}*/
}
}
总体思想:都分为有序区和无序区
选择排序:在无序区中找最小值。
最开始,有序区个数为0,无序区个数为数组元素个数
假设最小值为无序区第一个元素,然后用循环将无序区剩余元素与最小元素对比,如果后面的值比最小索引的值小,则将该元素的索引赋给minIndex。最后将minIndex索引的值与索引为I的值对换。
插入排序:将无序区的第一个元素插入到有序区的合适的位置