1.选择排序
2.冒泡排序
for (int i = 0; i < array.length - time; i++) {
int current = array[i];
int next = array[i + 1];
if (current > next) {
array[i] = next;
array[i + 1] = current;
}
}
每进行一次这个循环 ,每相邻的俩个数就会比较一次,如果前面的数字比后面的数字大,就调换位置。最后结果:每次将最大的那个值,放在最后一位。
package west;
public class Test {
public static void main(String[] args) {
int [] array = {1,2,4,5,3};
for (int time = 1; time <= array.length-1; time++) { //总共5个数,需要遍历四次,四次最大值放后面
for (int i = 0; i < array.length - time; i++) { //每次最大值放后面之后,那么最后那几位数字就不需要再进行比较了,这样就减少比较次数,减少运行次数
int current = array[i];
int next = array[i + 1];
if (current > next) {
array[i] = next;
array[i + 1] = current;
}
}
}
}
}
冒泡排序示意图:
3.插入排序:
package west;
public class Test {
public static void main(String[] args) {
int [] array = {1,2,4,5,3};
for (int i = 1; i < array.length; i++) { //只将数组的第一个数字,作为有效的遍历区间,其他数据都是待插入的数据
int data = array[i];
int j = 0;
for (; j < i; j++) {
if (array[j] > data) {
break;
}
}
//j=2
for (int k = i; k > j; k--) {
array[k] = array[k - 1];
}
array[j] = data;
}
for (int a : array) {
System.out.println(a);
}
}
}
每一次插入一个数字,比如要插入最后一个数字3:
①将数字3的位置找到:找到待插入的位置,遍历之前的有序区间(前四个数),如果是升序排序,那就找到一个比3这个数字大的数据所在的位置
②做移动:将找到位置后的元素往后移动一位
③将待插入的数字插入到该数组就行
插入排序示意图: