insertion sort


See On Github

Data

Source Code

//
//  InsertionSort.h
//  Algorithms
//
//  Created by R3alFr3e on 1/16/14.
//  Copyright (c) 2014 R3alFr3e. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface InsertionSort : NSObject

+ (void)sort:(NSMutableArray *)array;

@end
//
//  InsertionSort.m
//  Algorithms
//
//  Created by R3alFr3e on 1/16/14.
//  Copyright (c) 2014 R3alFr3e. All rights reserved.
//

#import "InsertionSort.h"

@implementation InsertionSort

/**
 * Insertion Sort
 *
 * @param array to be sorted by insertion sort
 */
+ (void)sort:(NSMutableArray *)array
{
    for(int i = 0; i < array.count; i++)
    {
        for(int j = i; j > 0; j--)
        {
            if([[array objectAtIndex:j] integerValue] < [[array objectAtIndex:j-1] integerValue])
            {
                id obj = [array objectAtIndex:j-1];
                [array replaceObjectAtIndex:j-1 withObject:[array objectAtIndex:j]];
                [array replaceObjectAtIndex:j withObject:obj];
            }
            else
                break;
        }
    }
}

@end
//
//  InsertionSort_Tests.m
//  InsertionSort Tests
//
//  Created by R3alFr3e on 1/16/14.
//  Copyright (c) 2014 R3alFr3e. All rights reserved.
//

#import <XCTest/XCTest.h>
#import "InsertionSort.h"

@interface InsertionSort_Tests : XCTestCase

@end

@implementation InsertionSort_Tests

- (void)setUp
{
    [super setUp];
}

- (void)tearDown
{
    [super tearDown];
}

- (void)testInsertionSort
{
    NSMutableArray * array = [[NSMutableArray alloc] initWithArray:@[@1,@54,@5,@8,@2,@6]];
    [InsertionSort sort:array];
    NSMutableArray * sortedArray = [NSMutableArray arrayWithArray:@[@1,@2,@5,@6,@8,@54]];
    
    XCTAssertEqualObjects(array, sortedArray, @"Array didn't get sorted");
    
}

@end