The principle and code implementation of the [GO] bubble sort

Source: Internet
Author: User

Bubble sort principle: For an array of all elements of 22 comparison, occurs greater than the transformation array subscript is ascending sort, occurs less than the transformed data subscript is descending sort

For example, given an array of [1,-2, 3,-4], for our requirements, 22 compared to the subscript transformation is ascending, after the first comparison, the maximum value of 3 will be moved to the rightmost array, the entire array of comparisons and the number of times the transformation has a regular to follow

After a few comparisons, the entire array is transformed into an ascending array

The code is implemented as follows

Package Mainimport ("Math/rand"    " Time"    "FMT") Func main () {rand. Seed (time. Now (). Unixnano ())varATen]intN:=Len (a) fmt. Println ("From ...")     forI: =0; I < n; i++{A[i]= Rand. INTN ( -) fmt. Printf ("%d,", A[i])} Fmt. Println ("\ n")     forI: =0; I < n1; i++ {         forJ: =0; J <n-1-I.; J + + {            ifA[J] > a[j+1] {a[j], a[j+1] = a[j+1], A[j]}}} fmt. Println ("order to ....")     forI: =0; I < n; i++{fmt. Printf ("%d,", A[i])}}

The code execution results are as follows

 from  ...  -  -  the  - 2  the  +  the  -  the , order to .... 2  -  the  the  -  +  -  -  the  the

The principle and code implementation of the

[GO] bubble sort

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.