|
| 1 | +package class01; |
| 2 | + |
| 3 | +public class Code07_Sort { |
| 4 | + |
| 5 | + public static void swap(int[] arr, int i, int j) { |
| 6 | + int tmp = arr[j]; |
| 7 | + arr[j] = arr[i]; |
| 8 | + arr[i] = tmp; |
| 9 | + } |
| 10 | + |
| 11 | + public static void selectSort(int[] arr) { |
| 12 | + if (arr == null || arr.length < 2) { |
| 13 | + return; |
| 14 | + } |
| 15 | + int N = arr.length; |
| 16 | + for (int i = 0; i < N; i++) { |
| 17 | + int minValueIndex = i; |
| 18 | + for (int j = i + 1; j < N; j++) { |
| 19 | + minValueIndex = arr[j] < arr[minValueIndex] ? j : minValueIndex; |
| 20 | + } |
| 21 | + swap(arr, i, minValueIndex); |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + public static void bubbleSort(int[] arr) { |
| 26 | + if (arr == null || arr.length < 2) { |
| 27 | + return; |
| 28 | + } |
| 29 | + int N = arr.length; |
| 30 | + for (int end = N - 1; end >= 0; end--) { |
| 31 | + for (int second = 1; second <= end; second++) { |
| 32 | + if (arr[second - 1] > arr[second]) { |
| 33 | + swap(arr, second - 1, second); |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + public static void insertSort1(int[] arr) { |
| 40 | + if (arr == null || arr.length < 2) { |
| 41 | + return; |
| 42 | + } |
| 43 | + int N = arr.length; |
| 44 | + for (int end = 1; end < N; end++) { |
| 45 | + int newNumIndex = end; |
| 46 | + while (newNumIndex - 1 >= 0 && arr[newNumIndex - 1] > arr[newNumIndex]) { |
| 47 | + swap(arr, newNumIndex - 1, newNumIndex); |
| 48 | + newNumIndex--; |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + public static void insertSort2(int[] arr) { |
| 54 | + if (arr == null || arr.length < 2) { |
| 55 | + return; |
| 56 | + } |
| 57 | + int N = arr.length; |
| 58 | + for (int end = 1; end < N; end++) { |
| 59 | + for (int pre = end - 1; pre >= 0 && arr[pre] > arr[pre + 1]; pre--) { |
| 60 | + swap(arr, pre, pre + 1); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + public static void printArray(int[] arr) { |
| 66 | + for (int i = 0; i < arr.length; i++) { |
| 67 | + System.out.print(arr[i] + " "); |
| 68 | + } |
| 69 | + System.out.println(); |
| 70 | + } |
| 71 | + |
| 72 | + public static void main(String[] args) { |
| 73 | + int[] arr = { 7, 1, 3, 5, 1, 6, 8, 1, 3, 5, 7, 5, 6 }; |
| 74 | + printArray(arr); |
| 75 | + insertSort2(arr); |
| 76 | + printArray(arr); |
| 77 | + } |
| 78 | + |
| 79 | +} |
0 commit comments