Last active
November 20, 2016 19:34
-
-
Save justinHowlett/5834773 to your computer and use it in GitHub Desktop.
Bubble sort in Objective-C
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
-(void)bubbleSortArray:(NSMutableArray*)unsortedArray{ | |
while (TRUE) { | |
BOOL hasSwapped = NO; | |
for (int i=0; i<unsortedArray.count; i++){ | |
/** out of bounds check */ | |
if (i < unsortedArray.count-1){ | |
NSUInteger currentIndexValue = [unsortedArray[i] intValue]; | |
NSUInteger nextIndexValue = [unsortedArray[i+1] intValue]; | |
if (currentIndexValue > nextIndexValue){ | |
hasSwapped = YES; | |
[self swapFirstIndex:i withSecondIndex:i+1 inMutableArray:unsortedArray]; | |
} | |
} | |
} | |
/** already sorted, break out of the while loop */ | |
if (!hasSwapped){ | |
break; | |
} | |
} | |
NSLog(@"sorted array is %@",unsortedArray); | |
} | |
-(void)swapFirstIndex:(NSUInteger)firstIndex withSecondIndex:(NSUInteger)secondIndex inMutableArray:(NSMutableArray*)array{ | |
NSNumber* valueAtFirstIndex = array[firstIndex]; | |
NSNumber* valueAtSecondIndex = array[secondIndex]; | |
[array replaceObjectAtIndex:firstIndex withObject:valueAtSecondIndex]; | |
[array replaceObjectAtIndex:secondIndex withObject:valueAtFirstIndex]; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Don't ever use this. Just for learning.