- 冒泡排序
每轮循环确定最值;
public void bubbleSort(int[] nums){ int temp; boolean isSort = false; //优化,发现排序好就退出
for (int i = 0; i < nums.length-1; i++) { for (int j = 0; j < nums.length-1-i; j++) { //每次排序后能确定较大值
if(nums[j] > nums[j+1]){
isSort = true;
temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
}
} if(!isSort){ return;
} else {
isSort = false;
}
}
}
2. 选择排序
每次选出最值,再交换到边上;
public void selectSort(int[] nums){ for (int i = 0; i < nums.length-1; i++) { int index = i; int minNum = nums[i]; for (int j = i+1; j < nums.length; j++) { if(nums[j] < minNum){
minNum = nums[j]; index = j;
}
} if(index != i){
nums[index] = nums[i];
nums[i] = minNum;
}
}
}
3. 插入排序
对循环的每个数找到属于自己的位置插入;
public void insertionSort(int[] nums){ for (int i = 1; i < nums.length; i++) { int j = i; int insertNum = nums[i]; while(j-1 >= 0 && nums[j-1] > insertNum){
nu