1、冒泡排序
package com.basicsort; public class BubbleSort { public static void main(String[] args) { int[] arr = {3, 6, 7, 88, 5, 36, 22}; int[] res = sort(arr); for (int data : res) { System.out.print(data + " "); } } //冒泡排序 public static int[] sort(int[] arr) { boolean flag = false; int temp = 0; for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { flag = true;//表示有交换 temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } if(flag == false){//表示没有交换 break; }else{ flag = false; } } return arr; } }
2、选择排序
代码实现:
package com.basicsort; public class SelectSort { public static void main(String[] args) { int[] arr = {3, 6, 7, 88, 5, 36, 22}; int[] res = sort(arr); for (int data : res) { System.out.print(data + " "); } } public static int[] sort(int[] arr) { int min = 0; int temp = 0; for (int i = 1; i < arr.length; i++) { min = i; for (int j = i; j < arr.length; j++) { if (arr[min] > arr[j]) { min = j; } } temp = arr[min]; arr[min] = arr[i]; arr[i] = temp; } return arr; } }
3、插入排序
代码实现:
package com.basicsort; public class InsertSort { public static void main(String[] args) { int[] arr = {3, 6, 7, 88, 5, 36, 22}; int[] res = sort(arr); for (int data : res) { System.out.print(data + " "); } } public static int[] sort(int[] arr) { for (int i = 1; i < arr.length; i++) { int j = i; int targat = arr[j]; while (j > 0 && arr[j - 1] > targat) { arr[j] = arr[j - 1];//往后移一位 j--; } arr[j] = targat; } return arr; } }
4、快速排序
代码实现:
package com.basicsort; public class QuickSort { public static void main(String[] args) { int[] arr = {3, 6, 7, 88, 5, 36, 22, 1}; int[] res = sort(arr, 0, arr.length - 1); for (int data : res) { System.out.print(data + " "); } } public static int[] sort(int[] arr, int left, int right) { int l = left; int r = right; int midVal = arr[(left + right) / 2]; while (l < r) { while (midVal > arr[l]) { l = l + 1; } while (midVal < arr[r]) { r = r - 1; } if (l >= r) { break; } int temp = arr[l]; arr[l] = arr[r]; arr[r] = temp; if (arr[l] == midVal) { r = r - 1; } if (arr[r] == midVal) { l = l + 1; } } if (l == r) { l = l + 1; r = r - 1; } if (left < r) { sort(arr, left, r); } if (right > l) { sort(arr, l, right); } return arr; } }