数据结构-排序
冒泡排序:
public static void sort(int[] arr){
int temp = 0;
for (int i = 0; i <arr.length-1 ; i++) {
for (int j = 0; j <arr.length-1-i ; j++) {
//如果前面的数比后面的数大 则交换
if (arr[j]>arr[j+1]){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
//
System.out.println("第"+i+1+"次排序结果");
System.out.println(Arrays.toString(arr));
}
}
选择排序:
public static void sort(int[] arr){
for (int i = 0; i <arr.length-1 ; i++) {
int minIndex = i;
int min = arr[i];
for (int j = i+1; j < arr.length; j++) {
if (min>arr[j]){ //说明假定的最小值不是最小的
min = arr[j]; //重置min
minIndex = j; //重置minIndex
}
}
//将最小值 放在arr[0] 即交换
if (minIndex !=i){
arr[minIndex] = arr[i];
arr[i] =min;
}
System.out.println("第"+(i+1)+"次排序结果");
System.out.println(Arrays.toString(arr));
}
}
插入排序:
public static void sort(int[] arr){
for (int i = 0; i <arr.length ; i++) {
int insertVal = arr[i];
int insertIndex = i -1;
while (insertIndex >=0&& insertVal <arr[insertIndex]){
arr[insertIndex+1] = arr[insertIndex];
insertIndex --;
}
arr[insertIndex+1] = insertVal;
System.out.println("第"+(i+1)+"次排序结果");
System.out.println(Arrays.toString(arr));
}
}
|