• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips
You are here: Home / ios / Insertion Sort

Insertion Sort

July 3, 2014 By Ravi Shankar 2 Comments

Insertion Sort algorithm does the following

  • Keeps the sorted numbers from left to right.
  • Compares the left with right and interchanges the number if left is greater than right.

Here is code snippet of Insertion Sort in Swift.

[code language=”swift”]var inputArr:[Int] = [Int]()

// generate random numbers
for rIndex in 0..<10 {
inputArr.append(((Int(arc4random()) % 100)))
}

func insertionSort(var inputArray :[Int]) -> [Int] {
var jIndex:Int,kIndex:Int

for kIndex in 1.. 0 && inputArray[jIndex-1] >= temp ) {
inputArray[jIndex] = inputArray[jIndex-1]
–jIndex
}
inputArray[jIndex] = temp
}

return inputArray
}

insertionSort(inputArr)[/code]

Filed Under: ios, Mac, Programming, Xcode Tagged With: algorithm, insertion Sort, Swift, Xcode

Reader Interactions

Comments

  1. Laurent says

    July 4, 2015 at 4:02 pm

    Does not work, you cannot swap values doing this.

    Reply
    • rshankar says

      July 4, 2015 at 4:45 pm

      I have fixed the code which was written during Swift beta release. Can you pls try now and let me know if this is still an issue.

      Thanks.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

TwitterLinkedin

Recent Posts

  • How to block keywords in Jio broadband
  • How to disable opening an app automatically at login in Mac
  • How to set preferred Wifi network on Mac
  • Attribute Unavailable: Estimated section warning before iOS 11.0
  • How to recover Firefox password from Time Machine backup

Pages

  • About
  • Privacy Policy
  • Terms and Conditions

Copyright 2022 © rshankar.com

Terms and Conditions - Privacy Policy