Solution_912.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package com.sf.leetcode;
  2. import java.util.Arrays;
  3. public class Solution_912 {
  4. // 排序算法有哪些:比较类排序和非比较类排序
  5. // 比较类排序:冒泡 快排 插入 希尔 选择 堆 归并
  6. // 非比较类排序:桶 计数 基数
  7. // 选择排序
  8. // 找到数组中最小的元素,然后和第一个元素交换,继续找到剩余元素中的最小值,和第二个元素交换,以此类推
  9. // 时间复杂度 O(n^2)
  10. public static int[] selectionSort(int[] nums) {
  11. for (int i = 0; i < nums.length; i++) {
  12. // 记录当前的最小值 所在的索引位置
  13. int min = i;
  14. for (int j = i + 1; j < nums.length; j++) {
  15. if (nums[j] < nums[min]) {
  16. min = j;
  17. }
  18. }
  19. if (min != i) {
  20. int temp = nums[min];
  21. nums[min] = nums[i];
  22. nums[i] = temp;
  23. }
  24. }
  25. return nums;
  26. }
  27. // 插入排序
  28. // 对于一组有序数据,第一个元素是天然有序,从第二个元素开始,如果比第一个元素大,那么就可以直接放在后面
  29. // [2,4]
  30. // [1,2,4]
  31. // 时间复杂度 O(n^2)
  32. public static int[] insertionSort(int[] nums) {
  33. for (int i = 1; i < nums.length; i++) {
  34. // 从当前位置往前遍历
  35. for (int j = i; j > 0; j--) {
  36. // 如果当前元素比前一个元素大 结束处理
  37. if (nums[j] > nums[j - 1]) break;
  38. int temp = nums[j];
  39. nums[j] = nums[j - 1];
  40. nums[j - 1] = temp;
  41. }
  42. }
  43. return nums;
  44. }
  45. // 冒泡排序
  46. // 两两比较相邻元素 将更大的元素后移 一轮冒泡后确保最大的元素在最后一个位置
  47. public static int[] bubbleSort(int[] nums) {
  48. for (int i = 0; i < nums.length - 1; i++) {
  49. for (int j = 0; j < nums.length - 1 - i; j++) {
  50. // 如果当前元素 比 后一个元素大 交换
  51. if (nums[j] > nums[j + 1]) {
  52. int temp = nums[j];
  53. nums[j] = nums[j + 1];
  54. nums[j + 1] = temp;
  55. }
  56. }
  57. }
  58. return nums;
  59. }
  60. public static void main(String[] args) {
  61. int[] nums = new int[]{3, 4, 5, 2, 1, 6, 7, 8, 9};
  62. // selectionSort(nums);
  63. // insertionSort(nums);
  64. bubbleSort(nums);
  65. System.out.println(Arrays.toString(nums));
  66. }
  67. }