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