Skip to content

Instantly share code, notes, and snippets.

@keitaito
Created September 11, 2015 08:31
Show Gist options
  • Save keitaito/626eeeaa4cc56ec53336 to your computer and use it in GitHub Desktop.
Save keitaito/626eeeaa4cc56ec53336 to your computer and use it in GitHub Desktop.
SelectionSort
//
// 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