Skip to content

Instantly share code, notes, and snippets.

@romyilano
Forked from justinHowlett/gist:5834773
Created January 21, 2014 02:14
Show Gist options
  • Save romyilano/8533289 to your computer and use it in GitHub Desktop.
Save romyilano/8533289 to your computer and use it in GitHub Desktop.
-(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