Skip to content

Instantly share code, notes, and snippets.

@tmdvs tmdvs/bubble.swift
Last active Aug 10, 2018

Embed
What would you like to do?
Bubble sort in Swift
// An Example of a bubble sort algorithm in Swift
//
// Essentialy this algorithm will loop through the values up to
// the index where we last did a sort (everything above is already in order/sorted)
// comparing a one value to the value before it. If the value before it is higher,
// swap them, and note the highest swap index. On the next iteration of the loop we
// only need to go as high as the previous swap.
import Foundation
var array = [5,3,4,6,8,2,9,1,7,10,11]
var sortedArray = NSMutableArray(array: array)
var sortedAboveIndex = array.count // Assume all values are not in order
do {
var lastSwapIndex = 0
for ( var i = 1; i < sortedAboveIndex; i++ ) {
if (sortedArray[i - 1].integerValue > sortedArray[i].integerValue) {
sortedArray.exchangeObjectAtIndex(i, withObjectAtIndex: i-1)
lastSwapIndex = i
}
}
sortedAboveIndex = lastSwapIndex
} while (sortedAboveIndex != 0)
// [5, 3, 4, 6, 8, 2, 9, 1, 7, 10, 11]
println(array)
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
println(sortedArray as Array)
@Antuaaan

This comment has been minimized.

Copy link

Antuaaan commented Sep 26, 2016

Getting two warnings on line 18 , C-style for statement and ++ are both deprecated. But otherwise it works like a charm!

@gsingh0616

This comment has been minimized.

Copy link

gsingh0616 commented Nov 13, 2016

some touch-ups:

`
var array = [5,3,4,6,8,2,9,1,7,10,11]
var sortedArray = Array(array)

var sortedAboveIndex = array.count // Assume all values are not in order

var lastSwapIndex = 0

//repeat {
for i in 1 ..< sortedAboveIndex {
if ((sortedArray[i - 1] ) > (sortedArray[i] )) {
swap(&sortedArray[i], &sortedArray[i - 1])
lastSwapIndex = i
}
}
sortedAboveIndex = lastSwapIndex

//} while (sortedAboveIndex != 0)

// [5, 3, 4, 6, 8, 2, 9, 1, 7, 10, 11]
print(array)

// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

print(sortedArray)`

@jecht83

This comment has been minimized.

Copy link

jecht83 commented Jan 29, 2017

Swift 3

var array = [5,3,4,6,8,2,9,1,7,10,11]
var sortedArray = NSMutableArray(array: array)
var sortedAboveIndex = array.count
var swaps = 0

repeat {
  var lastSwapIndex = 0
  
  for i in 1..<sortedAboveIndex {
    if (sortedArray[i - 1] as! Int) > (sortedArray[i] as! Int) {
      sortedArray.exchangeObject(at: i, withObjectAt: i-1)
      lastSwapIndex = i
      swaps += 1
    }
  }

  sortedAboveIndex = lastSwapIndex
  
} while (sortedAboveIndex != 0)

// [5, 3, 4, 6, 8, 2, 9, 1, 7, 10, 11]
print(array)

// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print(sortedArray as Array)

print("Array is sorted in \(swaps) swaps.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.