Computing the number of swaps in insertion sort

Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as “Quick Sort”, “Heap Sort”, or “Merge Sort”. However, insertion sort provides several advantages: simple implementation, efficient for (quite) small data sets, O(1)O(1) extra space.
When humans manually sort something (for example, a deck of playing cards), most use a method that is similar to insertion sort.
Source: Wikipedia
Although it is one of the elementary sorting algorithms with O(n2)O(n2) worst-case time, insertion sort is the algorithm of choice either when the data is nearly sorted (because it is adaptive) or when the problem size is small (because it has low overhead).
For these reasons, and because it is also stable, insertion sort is often used as the recursive base case (when the problem size is small) for higher overhead divide-and-conquer sorting algorithms, such as “Merge Sort” or “Quick Sort”.
Visualization by David R. Martin: http://www.sorting-algorithms.com/insertion-sort

Problem

Insertion sort is a simple algorithm with quadratic running time that builds the final sorted array one item at a time.
Insertion Sort - 图1
Given: A positive integer n≤103n≤103 and an array A[1..n]A[1..n] of integers.
Return: The number of swaps performed by insertion sort algorithm on A[1..n]A[1..n].

Sample Dataset

  1. 6
  2. 6 10 4 5 1 2

Sample Output

  1. 12
  1. from typing import List
  2. def insertSort(nums: List[int]) -> int:
  3. n = len(nums)
  4. cnt = 0
  5. for i in range(1, n):
  6. k = i # 插入起始
  7. while k > 0 and nums[k-1] > nums[k]: # ascending
  8. nums[k-1], nums[k] = nums[k], nums[k-1]
  9. k -= 1
  10. cnt += 1
  11. print(nums)
  12. return cnt
  13. print(insertSort([6, 10, 4, 5, 1, 2]))

Discussion

For this problem, it is enough to implement the pseudocode above with a quadratic running time and to count the number of swaps performed. Note however that there exists an algorithm counting the number of swaps in Insertion Sort - 图2.
Note also that Insertion Sort is an in-place algorithm as it only requires storing a few counters.

见评论区的二叉搜索树查找(即交换多少次)并实现插入 ,当然这个过程是进行查找 次的同时 x 就是树中的节点,还进行插入操作。因而当 Insertion Sort - 图3 时,最坏时间复杂度为 Insertion Sort - 图4,比上面排序快很多!

  1. import java.util.Arrays;
  2. import java.util.List;
  3. class Node {
  4. private Node left, right;
  5. private int value;
  6. public Node(int value) {
  7. this.value = value;
  8. }
  9. public void setLeft(Node left) {
  10. this.left = left;
  11. }
  12. public void setRight(Node right) {
  13. this.right = right;
  14. }
  15. public Node getLeft() {
  16. return left;
  17. }
  18. public Node getRight() {
  19. return right;
  20. }
  21. public int getValue() {
  22. return value;
  23. }
  24. }
  25. class BinaryTree {
  26. private int swaps = 0;
  27. public BinaryTree(List<Integer> values) {
  28. Node root = new Node(values.get(0));
  29. for (int i = 1; i < values.size(); i++) {
  30. Node currentNode = new Node(values.get(i));
  31. insert(root, currentNode);
  32. count(root, currentNode);
  33. }
  34. }
  35. private void insert(Node root, Node node) {
  36. if(node.getValue() < root.getValue()){
  37. Node left = root.getLeft();
  38. if (left == null){
  39. root.setLeft(node);
  40. }
  41. else{
  42. insert(root.getLeft(), node);
  43. }
  44. }
  45. else{
  46. Node right = root.getRight();
  47. if (right == null){
  48. root.setRight(node);
  49. } else{
  50. insert(root.getRight(), node);
  51. }
  52. }
  53. }
  54. private void count(Node root, Node currentNode){
  55. if(root != null){
  56. if(root.getValue() > currentNode.getValue()){
  57. swaps++;
  58. }
  59. count(root.getRight(), currentNode);
  60. count(root.getLeft(), currentNode);
  61. }
  62. }
  63. public int getSwaps(){
  64. return swaps;
  65. }
  66. }
  67. public class Main {
  68. public static void main(String[] args) {
  69. List<Integer> values= Arrays.asList(VALUES_SEPARATED_BY_COMMA);
  70. BinaryTree tree = new BinaryTree(values);
  71. System.out.println(tree.getSwaps());
  72. }
  73. }