A simple example of the bubble sort algorithm implemented by Swift code _swift

Source: Internet
Author: User

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!

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.