冒泡排序法

  1. package sort;
  2. /**
  3. * 直接插入排序
  4. *
  5. * @author shkstart 2018-12-17
  6. */
  7. public class InsertSort {
  8. public static void insertSort(int[] data) {
  9. System.out.println("开始排序");
  10. int arrayLength = data.length;
  11. for (int i = 1; i < arrayLength; i++) {
  12. int temp = data[i];
  13. if (data[i] - data[i - 1] < 0) {
  14. int j = i - 1;
  15. for (; j >= 0 && data[j] - temp > 0; j--) {
  16. data[j + 1] = data[j];
  17. }
  18. data[j + 1] = temp;
  19. }
  20. System.out.println(java.util.Arrays.toString(data));
  21. }
  22. }
  23. public static void main(String[] args) {
  24. int[] data = { 9, -16, 21, 23, -30, -49, 21, 30, 30 };
  25. System.out.println("排序之前:\n" + java.util.Arrays.toString(data));
  26. insertSort(data);
  27. System.out.println("排序之后:\n" + java.util.Arrays.toString(data));
  28. }
  29. }

快速排序

  1. public static void main(String[] args) {
  2. int[] arr = {9, -16, 30, 23, -30, -49, 25, 21, 30};
  3. System.out.println("排序之前:" + java.util.Arrays.toString(arr));
  4. quickSort(arr);
  5. System.out.println("排序之后:" + java.util.Arrays.toString(arr));
  6. }
  7. public static void quickSort(int[] arr) {
  8. subSort(arr, 0, arr.length - 1);
  9. }
  10. public static void subSort(int[] arr, int start, int end) {
  11. if (start < end) {
  12. int base = arr[start];
  13. int low = start;
  14. int high = end + 1;
  15. while (true) {
  16. while (high > start && arr[--high] >= base)
  17. ;
  18. while (low < end && arr[++low] <= base)
  19. ;
  20. if (low < high) {
  21. swap(arr, low, high);
  22. } else {
  23. break;
  24. }
  25. }
  26. swap(arr, start, high);
  27. subSort(arr, start, high - 1);
  28. subSort(arr, high + 1, end);
  29. }
  30. }
  31. public static void swap(int[] arr, int i, int j) {
  32. int temp = arr[i];
  33. arr[i] = arr[j];
  34. arr[j] = temp;
  35. }