The insertion sort implementation of the Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

This algorithm is still my postgraduate examination of the time to read. There are basically two kinds of insertion sort, head interpolation and tail interpolation method. The difference is whether the inserted position is the head or the tail.

Simply say the idea of inserting a sort:

    • Starting from the second element, the first element is considered to be orderly;
    • The element to be inserted is then sequentially compared to an ordered queue and inserted into the appropriate position;
    • Loop execution until the end of the traversal.

Golang the implementation of the package and I said above the strict grandmother's a little different. The traversed elements are compared backwards with the ordered queue in turn. If smaller than the ordered queue, exchange these two elements.

In contrast to traditional methods, the insertion step is also implemented by moving from back to forward. This method is a little simpler and does not need to declare temporary variables.

package mainimport "fmt"func insertionSort(data Interface, a, b int) {for i := a + 1; i < b; i++ {for j := i; j > a && data.Less(j, j-1); j-- {data.Swap(j, j-1)}}}type BySortIndex []intfunc (a BySortIndex) Len() int      { return len(a) }func (a BySortIndex) Swap(i, j int) { a[i], a[j] = a[j], a[i] }func (a BySortIndex) Less(i, j int) bool {return a[i] < a[j]}func main() {test0 := []int{49, 38, 65, 97, 76, 13, 27, 49}insertionSort(BySortIndex(test0), 0, len(test0))fmt.Println(test0)}type Interface interface {// Len is the number of elements in the collection.Len() int// Less reports whether the element with// index i should sort before the element with index j.Less(i, j int) bool// Swap swaps the elements with indexes i and j.Swap(i, j int)}

Please refer to the complete source code in this article.

    • "1" Data structure-Min

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.