Bubble Sort Principle
1. The data to be sorted, the two are compared, the small put in front, the big put behind
2. Step 1 for each pair of adjacent data in turn, and when sorted to the last element, we can guarantee that the data is the largest.
3. Repeat the above steps for all elements, in addition to the last one (why do we need to do this for all the elements except the last element), because the last element is already the largest one that does not need to be sorted, and because of the exchange of elements, the size of the exchanged elements is not necessarily larger than the preceding element, So it needs to be done again).
4 continues to repeat the steps of 3 for less and fewer elements until no pair of elements need to be compared.
Complexity of Time
We generally talk about the worst time system
N (n-1)/2 = O (n²)
Algorithm stability
the order of the same elements has not changed, so it is a stable sort algorithm
Import Cocoa
var array = [123,234,12,346,4,75,67,234,23,1233,3,5,986,98,567,345,234,234]
println (pre-sorted value:) For
item in array
{
var II = Item
println (ii)
} for
var i = 0; i < Array.count-1, ++i {for
var j = 0; J < arr Ay.count-1-I; ++j{
if ARRAY[J] > array[j + 1] {
var temp = array[j + 1]
array[j + 1] = Array[j]
array[j] = temp
}
}
println ("Sorted value:") for item in
array
{
var II = Item
println (ii)
}
Run Result:
The For loop here uses the traditional for loop method in C, please advise, and shoot bricks!