需求:数组元素为 9,1,2,3,4,5,6,7,8;如何让这列数组只排一次之后不再继续排序,因为除了第一个元素9之外,其他的都是有序的
2种实现方式,冒泡、选择
public class Sort {
public static void main(String[] args) {
// int[] array = new int[]{3, 2, 5, 8, 1, 9, 4, 6, 7};
int[] array = new int[]{9, 1, 2, 3, 4, 5, 6, 7, 8};
for (int i : array) {
System.out.print(i+" ");
}
System.out.println();
bubbleSort(array);
for (int i : array) {
System.out.print(i+" ");
}
}
/**
* 冒泡排序
*
* @param array
*/
public static void bubbleSort(int[] array) {
int count=0; //统计次数
for(int i=array.length-1;i>0;i--) {
boolean flag=true; //优化的标识; 如果没有变化,跳出循环
for (int j = 0; j < i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;//交换
flag=false;
}
}
if(flag){
break;
}
++count;
}
System.out.println("排序次数:"+count);
}
//选择排序
//3, 1, 5, 8, 2, 9, 4, 6, 7
//9, 1, 2, 3, 4, 5, 6, 7, 8
public static void selectSort(int[] array){
//将index作为最小值,找到最小值赋值给index
for(int i=0;i<array.length-1;i++) {
int index = i;
for (int j = i+1; j < array.length; j++) {
if (array[j] < array[index]) {
index = j;
}
}
/**
* 如果index==i,证明i就是最小值,那么不用替换数据
* 如果i不是最小值,就将i下标的元素与最小值index下标的元素替换
*/
if(index!=i) {//表示打到过最小值
int temp = array[i];
array[i] = array[index];
array[index] = temp;
}
}
}
}