1、冒泡排序
public class BoSort { /** * 交换 * @param arr * @param a * @param b */ public static void swap(int[] arr, int a, int b) { int temp = arr[a] ; arr[a] = arr[b]; arr[b] = temp; } /** * 核心排序 * @param arr */ public static void posort(int arr[]) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { swap(arr,j,j+1); } } } } /** * 打印输出 * @param arr */ public static void print( int arr[]) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+" "); } } public static void main(String[] args) { int arr[] = {1, 4, 7, 0, 5, 4, 9, 7,}; posort(arr); print(arr); } }
2、直接排序
public class DirectSort { public static void swap(int[] arr, int a, int b) { int temp = arr[a] ; arr[a] = arr[b]; arr[b] = temp; } public static void Directsort(int arr[]) { for (int i = 0; i < arr.length-1; i++) { for (int j = i; j >=0; j--) { if (arr[j] > arr[j+1]) { swap(arr,j,j+1); } } } } public static void print( int arr[]) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+" "); } } public static void main(String[] args) { int arr[] = {1, 4, 7, 0, 5, 4, 9, 7,}; Directsort(arr); print(arr); } }
3、选择排序
public class SelectSort { public static void swap(int[] arr, int a, int b) { int temp = arr[a] ; arr[a] = arr[b]; arr[b] = temp; } public static void selectSort(int arr[]) { for (int i = 0; i < arr.length-1; i++) { int min = i; for (int j = i; j < arr.length; j++) { if (arr[min] > arr [j]) { min = j; } } if (min != i){ swap(arr,min,i); } } print(arr); } public static void print( int arr[]) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i]+" "); } } public static void main(String[] args) { int arr[] = {1, 4, 7, 0, 5, 4, 9, 7,}; selectSort(arr); } }