入门排序(冒泡、选择、直接)
入门排序
新手入门级排序
1.冒泡排序
public class BolloSort {
public static void main(String[] args) {
int[] array = {
5, 4, 2, 6, 4, 21, 1};
System.out.println("排序前" + Arrays.toString(array));
for (int i = 0, len = arrays.length; i < len; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (arrays[j] > arrays[j + 1]) {
int temp = arrays[j];
arrays[j] = arrays[j + 1];
arrays[j + 1] = temp;
}
}
}
System.out.println("排序后" + Arrays.toString(array));
}
}
2.选择排序
public class SelectSort {
public static void main(String[] args) {
int[] array = {
5, 4, 2, 6, 4, 21, 1};
System.out.println("排序前" + Arrays.toString(array));
for (int tian = array.length - 1; tian >= 0; tian--) {
int max = array[0];
int maxIndex = 0;
for (int i = 0; i <= tian; i++) {
if (array[i] > max) {
max = array[i];
maxIndex = i;
}
}
int temp = array[tian];
array[tian] = array[maxIndex];
array[maxIndex] = temp;
}
System.out.println("排序后" + Arrays.toString(array));
}
}
3.插入排序
public class InsertSotr {
public static void main(String[] args) {
int[] array = {5, 4, 2, 6, 4, 21, 1};
System.out.println("排序前" + Arrays.toString(array));
for (int i = 0; i < array.length; i++) {
int lastIndex = i-1;
int v = array[i];
while(lastIndex>-1&&v<array[lastIndex]){
array[lastIndex+1] =array[lastIndex];
lastIndex--;
}
array[lastIndex+1] = v;
}
System.out.println("排序前" + Arrays.toString(array));
}
}