Go language Implementation sorting algorithm

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

One: Insert sort

1: Algorithm Description

    1. Starting with the first element, the element can be thought to have been sorted

    2. Takes the next element and scans the sequence of elements that have been sorted from back to forward

    3. If the element (sorted) is greater than the new element, move the element to the next position

    4. Repeat step 3 until you find the sorted element is less than or equal to the position of the new element

    5. After inserting a new element into the position

    6. Repeat step 2~5

2: Code implementation

Func Insertsort (p []int) {

For i: = 1; i < Len (p); i++ {

For j: = I-1; J >= 0 && p[j+1] < p[j]; j--{

P[J+1], p[j] = P[j], p[j+1]

}

}

}

Two: Bubble sort

1: Algorithm Description

    1. Compares the adjacent elements. If the first one is bigger than the second one, swap them both.

    2. Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. When this is done, the final element will be the maximum number.

    3. Repeat the above steps for all elements, except for the last one.

    4. Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.

2: Program Implementation

Func Bubblesort (p []int) {

For i: = 1; i < Len (p)-1; i++ {

For j: = 0; J < Len (p)-I.; J + + {

If P[J] > p[j+1] {

P[J+1], p[j] = P[j], p[j+1]

}

}

}

}

Related Article

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.