Java与算法之(9) - 直接插入排序

时间:2024-04-15 16:25:06

直接插入排序是最简单的排序算法,也比较符合人的思维习惯。想像一下玩扑克牌抓牌的过程。第一张抓到5,放在手里;第二张抓到3,习惯性的会把它放在5的前面;第三张抓到7,放在5的后面;第四张抓到4,那么我们会把它放在3和5的中间。

Java与算法之(9) - 直接插入排序

直接插入排序正是这种思路,每次取一个数,从前向后找,找到合适的位置就插进去。

代码也非常简单:

  1. /**
  2. * 直接插入排序法
  3. * Created by autfish on 2016/9/18.
  4. */
  5. public class InsertSort {
  6. private int[] numbers;
  7. public InsertSort(int[] numbers) {
  8. this.numbers = numbers;
  9. }
  10. public void sort() {
  11. int temp;
  12. for(int i = 1; i < this.numbers.length; i++) {
  13. temp = this.numbers[i]; //取出一个未排序的数
  14. for(int j = i - 1; j >= 0 && temp < this.numbers[j]; j--) {
  15. this.numbers[j + 1] = this.numbers[j];
  16. this.numbers[j] = temp;
  17. }
  18. }
  19. System.out.print("排序后: ");
  20. for(int x = 0; x < numbers.length; x++) {
  21. System.out.print(numbers[x] + "  ");
  22. }
  23. }
  24. public static void main(String[] args) {
  25. int[] numbers = new int[] { 4, 3, 6, 2, 7, 1, 5 };
  26. System.out.print("排序前: ");
  27. for(int x = 0; x < numbers.length; x++) {
  28. System.out.print(numbers[x] + "  ");
  29. }
  30. System.out.println();
  31. InsertSort is = new InsertSort(numbers);
  32. is.sort();
  33. }
  34. }

测试结果:

  1. 排序前: 4  3  6  2  7  1  5
  2. 排序后: 1  2  3  4  5  6  7

直接插入排序的时间复杂度,最好情况是O(n),最坏是O(n^2),平均O(n^2)。