Review articles algorithms: insertion sort from theory to practice


I. Introduction:
Second, the algorithm description
  • Brief (descending order): 1 ~ N one has to be sorted elements
  • Note: x behind said element or elements and the subscript y x or y sequence corresponding to the elements
  • 1, take x (case x = 1) element as an element of the current to be compared;
  • 2, so that y = x;
  • 3, taken y-1 y element is compared with the element, if the element is greater than y-1 y position of the element, the element y and y-1 switching elements;
  • 4, it is determined whether y is greater than 0, if greater than 0, execution continues to repeat step 3;
  • 5, it is determined whether the x + 1 is greater than the length of the sequence, if not, the x = x + 1; we proceed to step 2, otherwise the end of the sort
  • As can be seen from the above, flashback sort feature is that the front element with the sort that have been sorted sequence of elements, so when x is equal to the last element of the sequence and when x sorted Hershey, at which time the sequence will Sort finished.
Third, code implementation
  • Code below, see the inside part of the code SortUtils algorithm review articles: Selection Sort :

    class InsertSortDemo {
        fun sort(list: Array<Comparable<Any>>) {
            for (i in 1..(list.size - 1)) {
                var j = i;
                while (j > 0 && SortUtils.less(list[j], list[j - 1])) {
                    SortUtils.exchange(list, j, j - 1);
                    j--;
                }
            }
        }
    }
  • Test code:

    fun main(args: Array<String>) {
        var list: Array<String> = arrayOf("S", "O", "R","T", "E", "X","A","M","P","L","E");
        var insertSort = InsertSortDemo();
        var startTime = System.currentTimeMillis();
        insertSort.sort(list as Array<Comparable<Any>>)
        var endTime = System.currentTimeMillis();
        var costTime = endTime - startTime;
        println("花费时间: $costTime")
    }
IV Summary:
  • Insertion Sort
  • Features: Elements of the left always order
  • Switching elements times: 0 is the lowest (the list is to be sorted list order) up to N ^ 2/2 times,
  • Average number of exchanges: N ^ 2/4 times
  • Comparison of the number of elements: preferably N-1 times (the list is to be sorted list order), the worst of N ^ 2/2 times the average of N ^ 2/4 times
  • More suitable for use in some scenarios insertion sort:
    • 1, each element of the array a short distance from his final position, so that the number of comparisons and the number of exchanges are relatively small
    • 2, only a few elements in the array of order

Related Reading

Guess you like

Origin www.cnblogs.com/cnblogzaizai/p/11570488.html