Insert sort and bubble sort (Swift version)

Source: Internet
Author: User
Tags comparable

Insert sort (only record code is not analyzed in detail)

Insert sort inserts the input elements into the sorted queue, and the contrast is the forward

Code:

Func insertsort<elem:comparable> (_ arr:inout [Elem]) {
    for I in 1...arr.count-1 {
&N bsp;       let tmp = Arr[i]
       
         for J in (0...i-1). Reversed () {
             if (J > 0 && arr[j] > tmp) {
                 arr[j + 1] = Arr[j]
            } else {
                 arr[j + 1] = tmp
                 break
           }
        
   }
}

Bubble Sort:

Func bubblesort<elem:comparable> (_ arr:inout [Elem]) {
Func Swap (_ A:inout Elem, _ b:inout Elem) {
Let TMP = a
A = b
b = tmp
}

For I in (1...arr.count-1). Reversed () {
For J in 0...i-1 {
If ARR[J] > arr[j+1] {
Swap (&arr[j], &arr[j+1])
}
}
}
}

Insert sort and bubble sort (Swift version)

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.