之前对冒泡有点误解,之前没有进行相邻数冒泡,而是全局直接选最大/最小。
public class Main { private static int arr[]; public static void swap(int flag[], int max, int i) { int temp = flag[max]; flag[max] = flag[i]; flag[i] = temp; } public static void Bubble(int ans[], int n) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < n-1; j++) { if(ans[j+1]<ans[j]) swap(ans, j+1 ,j); } n--; } } public static void main(String[] args) { arr = new int[] { 25, 30, 11, 7, 22, 16, 18, 33, 40, 55 }; Bubble(arr, arr.length); for(int i = 0 ; i < arr.length ; i++) { System.out.println(arr[i]); } } }
直接选择排序
public class Main { private static int arr[]; public static void swap(int flag[], int max, int i) { int temp = flag[max]; flag[max] = flag[i]; flag[i] = temp; } public static void choose(int ans[], int n) { for (int i = 0; i < n; i++) { int min = ans[i]; int pos = i; for (int j = i+1; j < n; j++) { if(ans[j]<min){ pos = j; min = ans[j]; } } swap(ans, pos , i); } } public static void main(String[] args) { arr = new int[] { 25, 30, 11, 7, 22, 16, 18, 33, 40, 55 }; choose(arr, arr.length); for(int i = 0 ; i < arr.length ; i++) { System.out.println(arr[i]); } } }
直接插入排序
package leetcode; public class Main { private static int arr[]; public static void insert(int ans[], int n) { for(int i = 1 ; i < n ; i++) { int j = i; int temp = ans[j]; while(j-1>=0&&temp<ans[j-1]) { ans[j] = ans[j-1]; j--; } ans[j] = temp; } } public static void main(String[] args) { arr = new int[] { 25, 30, 11, 7, 22, 16, 18, 33, 40, 55 }; insert(arr, arr.length); for(int i = 0 ; i < arr.length ; i++) { System.out.println(arr[i]); } } }