Created
April 1, 2021 19:28
-
-
Save Roshankumar350/39416a4c87fb0f0a9f82440780484666 to your computer and use it in GitHub Desktop.
Sorting: Understanding Bubble Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func bubbleSort(forInput input: inout [Int]) { | |
let uptoEndIndex = input.count - 1 | |
for rearIndex in 0...uptoEndIndex { | |
var isAllSorted = true | |
for frontIndex in 0..<uptoEndIndex - rearIndex { | |
let currentRunning = frontIndex | |
let currentRunningAheadByOne = currentRunning + 1 | |
if input[currentRunning] > input[currentRunningAheadByOne] { | |
input.swapAt(currentRunning, currentRunningAheadByOne) | |
isAllSorted = false | |
} | |
} | |
if isAllSorted { | |
break | |
} | |
} | |
} | |
var unOrderArray = [5,2,13,7,11,3] | |
bubbleSort(forInput: &unOrderArray) | |
print(unOrderArray) | |
func optimisedBubbleSort(forInput input: inout [Int]) { | |
let uptoIndex = input.count - 1 | |
for rearIndex in 0...uptoIndex { | |
// Assuming all elements are sorted | |
var isAllSorted = true | |
for frontIndex in 0..<uptoIndex - rearIndex { | |
let currentRunning = frontIndex | |
let currentRunningAheadByOne = currentRunning + 1 | |
if input[currentRunning] > input[currentRunningAheadByOne] { | |
isAllSorted = false | |
input.swapAt(currentRunning, currentRunningAheadByOne) | |
continue | |
} | |
} | |
// If our assumptions holds true, Then array is sorted. No need go for next Pass | |
if isAllSorted { | |
break | |
} | |
} | |
} | |
optimisedBubbleSort(forInput: &unOrderArray) | |
print(unOrderArray) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment