public class code_select { // 冒泡排序 public static void bubbleSort(int []arr){ if (arr == null || arr.length < 2){ return; } int N = arr.length; // 把外面的边界确定好来 for(int end = N - 1 ; end >= 0; end--){ // 0 1 1 2 2 3,打个比方让0 1 比较 for (int second = 1; second <= end; second++) { if(arr[second-1] > arr[second]){ swap(arr, second - 1 , second); } } } } public static void swap(int[] arr, int i , int j){ int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } public static void printArray(int [] arr){ for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void main(String[] args) { int[] arr = {7, 1, 2, 3, 5, 8}; printArray(arr); bubbleSort(arr); printArray(arr); }}
java冒泡排序
时间:2023-06-18
相关推荐