• Skip to main content
  • Skip to primary sidebar

Ravi Shankar

Tweaking Apps

  • Swift
  • Tech Tips
You are here: Home / Apple / Bubble Sort

Bubble Sort

June 25, 2014 By Ravi Shankar 2 Comments

The best way to practice a new language is to write more programs using that language. Here is a Bubble Sort program written in Swift Programming language.

Data to be sorted = {12, 56, 32, 23, 67, 87, 45, 23,10, 11}

Bubble Sort

Bubble Sort is performed by comparing two number starting from the left and swapping the greater number to the right. And then moves one position to right until end.

Bubble Sort in Swift

This has a function named swapNumbers for swapping the values of array for the given two indexes. Then the for loop that compares the two numbers starting from left to right and uses swapNumbers function to swap the values if the left is greater than right.

var inputArr = [12,56,32,23,67,87,45,23,10,11]

func swapNumbers(index1 :Int,index2: Int) {

let temp = inputArr[index1]

inputArr[index1] = inputArr[index2]

inputArr[index2] = temp

}

for var index: Int = inputArr.count–1; index > 1; –index {

for var jIndex: Int = 0; jIndex < index; ++jIndex {

if inputArr[jIndex] > inputArr[jIndex + 1] {

swapNumbers(jIndex, jIndex+1)

}

}

}

inputArr

Here is the Swift code tested in Playground, you can see the sorted results in the sidebar

Bubble Sort in Swift Programming language

Filed Under: Apple, ios, Programming, Xcode Tagged With: Apple, Swift, Untitled, Xcode

Reader Interactions

Comments

  1. Nate says

    August 8, 2014 at 9:10 pm

    I get the whole thing to work with out any errors but I can’t get it to display my sorted data. I have everything the same but once I type inputArr after the end function bracket nothing happens. It displays how many times it took to sort everything but not the completed array. I am on beta 5 not sure if that makes a difference or not but any help would be great.

    Reply
  2. Dzung says

    September 11, 2014 at 6:45 am

    @Nate: You should edit this line:
    for var index: Int = inputArr.count-1; index > 1; –index {
    to:
    for var index: Int = inputArr.count-1; index > 1; –-index {

    The author made a typos.

    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