文章目录
1、原理
选择排序是在一组待排序的数组中选择一个最小(大)的数排在序列头,然后在剩下的待排序的数中选择最小(大)的数排在序列尾,以此类推,直到待排数目为0。
代码实现
public class Demo2 {
public static void main(String[] args) {
int[] ab ={3,8,2,6,9,7,1,4,0,5};
D(ab);
for (int i = 0; i <ab.length ; i++) {
System.out.print(ab[i]);
}
}
public static void D(int[] ab){
for (int i = 0; i <ab.length ; i++) {
int minpos = i;
for (int j = i; j <ab.length ; j++) {
if(ab[j]<ab[minpos]){
//minpos=i;
E(ab,minpos,j);
}
}
}
}
public static void E(int[] a,int c,int b){
int t = a[c];
a[c]=a[b];
a[b]=t;
}
}
优化代码
优化思想:每一轮找出一个最小数和一个最大数,最小数放在第一个位置,最大数放在最后一个位置可以减少循环的次数
public class Demo2 {
public static void main(String[] args) {
int[] ab ={3,8,2,6,9,7,1,4,0,5};3
E(ab);
for (int i = 0; i <ab.length ; i++) {
System.out.print(ab[i]);
}
}
public static void E(int[] ab){
int min = 0;
int max = 0;
int left = 0;
int right = ab.length-1;
while (left<right){
min = left;
max = right;
//找到最大值,最小值的小标
for(int i = left;i<right;i++){
if(ab[i]<ab[min]){
min = i;
}
if(ab[i]>ab[max]){
max = i;
}
}
//将最大值放在最右
if(max!=right){
int temp = ab[max];
ab[max] = ab[right];
ab[right] = temp;
}
//防止最小值在最大值将要交换的位置上
if(min == right){
max = min;
}
//将最小值放在左侧
if(min!=left){
int temp = ab[min];
ab[min] = ab[left];
ab[left] = temp;
}
left++;
right--;
}
}
}