Created
September 11, 2015 08:31
-
-
Save keitaito/626eeeaa4cc56ec53336 to your computer and use it in GitHub Desktop.
SelectionSort
This file contains 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
// | |
// SelectionSort.m | |
// KIObjcAlgorithms | |
// | |
// Created by Keita on 9/11/15. | |
// Copyright © 2015 Keita Ito. All rights reserved. | |
// | |
#import "SelectionSort.h" | |
@implementation SelectionSort | |
- (void)selectionSort:(NSMutableArray *)array { | |
for (NSUInteger i = 0; i < array.count; i++) { | |
NSUInteger minIndex = [self minimumIndexOfArray:array startIndex:i]; | |
[self swapElementsOfArray:array WithIndex:i andAnotherIndex:minIndex]; | |
} | |
} | |
- (void)swapElementsOfArray:(NSMutableArray *)array WithIndex:(NSUInteger)firstIndex andAnotherIndex:(NSUInteger)secondIndex { | |
NSNumber *temp = array[firstIndex]; | |
array[firstIndex] = array[secondIndex]; | |
array[secondIndex] = temp; | |
} | |
- (NSUInteger)minimumIndexOfArray:(NSMutableArray *)array startIndex:(NSUInteger)startIndex { | |
NSUInteger minIndex = startIndex; | |
NSNumber *minValue = array[startIndex]; | |
for (NSUInteger i = minIndex + 1; i < array.count; i++) { | |
if (array[i] < minValue) { | |
minIndex = i; | |
minValue = array[i]; | |
} | |
} | |
return minIndex; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reference: https://www.khanacademy.org/computing/computer-science/algorithms/sorting-algorithms/p/challenge-implement-selection-sort