Note:- I have defined it as a static method in the SimpleAlgorithms class. And also this is for Learning Purpose only! :-)
~~~~~~~~~~~ EDIT TO ADD IMPROVED IMPLEMENTATION ~~~~~~~~~~~~
Thanks to contributions of Zumry Mohamed and Martin R, I learned few things about Objective-C and also got chance to improve my implementation.
Things I learned:
NSArray methods
* sortedArrayUsingComparator: * compare: * exchangeObjectAtIndex:withObjectAtIndex:
And an optimization to the algorithm implementation to eliminate rounds of iterations through the elements even after they are really swapped and sorted out.
So following is my improved Bubble Sort Algorithm implementation in Objective-C:
+ (NSArray *) bubbleSort:(NSArray *) arrayToBeSorted ascendingOrder:(BOOL) sortInAscendingOrder {
// As we can't swap integers in a static array, make a mutable array out of the given static array.
NSMutableArray *muArrRaw = [[NSMutableArray alloc] initWithArray:arrayToBeSorted];
BOOL swapped;
NSUInteger n = [muArrRaw count];
// iterate through the array as rounds
do {
swapped = NO;
// iterate through each element of the array with the given range
for (NSUInteger j = 0; j + 1 < n; j++) {
// comparison
if (sortInAscendingOrder && [muArrRaw[j] compare:muArrRaw[j+1]] == NSOrderedDescending) {
[muArrRaw exchangeObjectAtIndex:j withObjectAtIndex:j+1];
swapped = YES;
} else if (!sortInAscendingOrder && [muArrRaw[j] compare:muArrRaw[j+1]] == NSOrderedAscending) {
[muArrRaw exchangeObjectAtIndex:j withObjectAtIndex:j+1];
swapped = YES;
}
}
} while (swapped);
// return the sorted array
return [muArrRaw copy];
}