Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Selection Sort #9

Closed
wants to merge 1 commit into from
Closed

Selection Sort #9

wants to merge 1 commit into from

Conversation

phelgo
Copy link

@phelgo phelgo commented Nov 23, 2015


for index in array.indices {
var indexOfMinimumValue = index
for innerIndex in index + 1..<array.count {
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I opted for a inner loop here, but maybe extracting this indexOfMinimumValue logic into a local function can be easier to follow.

@gmertk
Copy link
Owner

gmertk commented Nov 24, 2015

Thanks @phelgo! This could be nice:


func indexOfMinFrom(index: Int, array: [Int]) -> Int? {
    guard 0..<array.count ~= index else {
        return nil
    }

    var indexOfMin = index

    for i in index+1..<array.count where array[i] < array[indexOfMin] {
        indexOfMin = i
    }

    return indexOfMin
}

@phelgo
Copy link
Author

phelgo commented Nov 24, 2015

@gmertk Exactly 👍
Then the body of the algorithm can be as simple to follow as

for index in array.indices {
    if let indexOfMinimumValue = indexOfMinFrom(index, array) where indexOfMinimumValue != index {
        swap(&array[index], &array[indexOfMinimumValue])
}
return array

@gmertk gmertk closed this Nov 27, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants