Skip to content

Instantly share code, notes, and snippets.

@AnthonyBY
Created March 1, 2017 15:22
Show Gist options
  • Save AnthonyBY/9014c2b867dacfb5c5b4d4d68078e1af to your computer and use it in GitHub Desktop.
Save AnthonyBY/9014c2b867dacfb5c5b4d4d68078e1af to your computer and use it in GitHub Desktop.
HackerRank: Sorting: Bubble Sort (Swift 3)
import Foundation
// read the integer n
let n = Int(readLine()!)!
// read the array
var arr = readLine()!.components(separatedBy: " ").map{ Int($0)! }
var swapCount = 0
for i in 0...arr.count-1 {
for j in i...arr.count-1 {
if arr[i] > arr[j] {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp
swapCount += 1
}
}
}
print("Array is sorted in \(swapCount) swaps.")
print("First Element: \(arr.first!)")
print("Last Element: \(arr.last!)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment