[关闭]
@XQF 2018-03-07T22:53:47.000000Z 字数 1239 阅读 980

排序----插入排序

数据结构与算法


1.首发

把一个数组分为两个部分,前面是排序的场所,后面是原数组序列。每次从后面部分选出一个数与前面排好序的序列中的数进行比较,要是没有找到合乎条件的就说明这个数没办法插入,要么比前面排好序的序列所有数都大,要么都小。于是不动这个数,直接进行下一轮比较时,这个数被自动插入。

倘如找到了一个合乎条件的情况,那么保存下当前值。保存当前的索引。从这个索引往后的数值被移动。,。,。插入,。,实在是形容不出来了。

  1. public class Solution {
  2. public int[] insertSort(int[] nums) {
  3. if(nums==null||nums.length==0){
  4. return null;
  5. }
  6. for (int i = 1; i < nums.length; i++) {
  7. int p = 0;
  8. int temp = 0;
  9. boolean find = false;
  10. for (int j = 0; j < i; j++) {
  11. if (nums[i] < nums[j]) {
  12. find = true;
  13. temp = nums[i];
  14. p = j;
  15. break;
  16. }
  17. }
  18. if (find == true) {
  19. //这里移动的时候注意后面往前,。,。有坑
  20. for (int k = i; k > p; k--) {
  21. nums[k] = nums[k - 1];
  22. }
  23. nums[p] = temp;
  24. }
  25. }
  26. return nums;
  27. }
  28. public static void main(String[] args) {
  29. Solution solution = new Solution();
  30. int[] nums = {1, 2, 55, 6, 3, 2, 4, 5, 6, 8, 9, 0};
  31. System.out.println(Arrays.toString(solution.insertSort(nums)));
  32. }
  33. }

2.重构

  1. public class Solution {
  2. public int[] insertSort(int[] nums) {
  3. if (nums == null || nums.length == 0) {
  4. return null;
  5. }
  6. if (nums.length == 1) {
  7. return nums;
  8. }
  9. for (int i = 1; i < nums.length; i++) {
  10. int temp = nums[i];
  11. int j;
  12. for (j = i - 1; j >= 0; j--) {
  13. //这里用temp,不能在使用nums[i],有坑
  14. if (temp < nums[j]) {
  15. nums[j + 1] = nums[j];
  16. } else {
  17. break;
  18. }
  19. }
  20. nums[j + 1] = temp;
  21. }
  22. return nums;
  23. }
  24. public static void main(String[] args) {
  25. int[] nums = {1, 2, 55, 6, 3, 2, 4, 5, 6, 8, 9, 0};
  26. // int[] nums = {1, 2, 55, 6, 3};
  27. Solution solution = new Solution();
  28. System.out.println(Arrays.toString(solution.insertSort(nums)));
  29. }
  30. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注