Skip to content

Instantly share code, notes, and snippets.

@justinHowlett
Last active November 20, 2016 19:34
Show Gist options
  • Save justinHowlett/5834773 to your computer and use it in GitHub Desktop.
Save justinHowlett/5834773 to your computer and use it in GitHub Desktop.
Bubble sort in Objective-C
-(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];
}
@justinHowlett
Copy link
Author

Don't ever use this. Just for learning.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment