Skip to content

Instantly share code, notes, and snippets.

@Roshankumar350
Created April 13, 2021 07:32
Show Gist options
  • Save Roshankumar350/18d2db80bcb3955a1b289f0c6114ed7d to your computer and use it in GitHub Desktop.
Save Roshankumar350/18d2db80bcb3955a1b289f0c6114ed7d to your computer and use it in GitHub Desktop.
func selectionSort(forInput input: inout [Int]) {
let uptoIndex = input.count - 1
var currentRunningMaximumNumber = input[0]
for rearIndex in 0..<uptoIndex {
// Assuming all are sorted
var isAllSorted = true
// Assuming rearIndex is minimum Index
var currentRunningMinimumIndex = rearIndex
for frontIndex in (rearIndex+1)...uptoIndex {
// Will have maximum number so far.
if input[frontIndex] > currentRunningMaximumNumber {
currentRunningMaximumNumber = input[frontIndex]
}
// We will try to find minimum number's index.
guard input[currentRunningMinimumIndex] > input[frontIndex] else {
// Check if maximum number so far is still maxumum else it's not sorted
if currentRunningMaximumNumber > input[frontIndex] {
isAllSorted = false
}
continue
}
currentRunningMinimumIndex = frontIndex
}
// if both index are equal, You don't want to swap it.
guard currentRunningMinimumIndex == rearIndex else {
input.swapAt(currentRunningMinimumIndex, rearIndex)
continue
}
// If our assumption of all elements are sorted is true. We will break
guard isAllSorted else {
continue
}
break
}
}
@Roshankumar350
Copy link
Author

But our objective was to check the array is sorted once only.

Currently we are least concerned about cases, rather we are more concerned about can we exist if entire array is sorted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment