Returning a mutable copy of the temporary array makes no sense to me, perhaps you meant
return [muArrRaw copy];
to return an immutable array (as the return type of the method indicates).
The "proper" data type for array indices is NSUInteger
, not int
.
In
if (j < ([muArrRaw count] - 1) && [[muArrRaw objectAtIndex:j] intValue] > [[muArrRaw objectAtIndex:(j + 1)] intValue]) {
you can get rid of the extra check j < ([muArrRaw count] - 1)
if the
outer loop starts with i = 1
.
Also [muArrRaw objectAtIndex:j]
can be shortened to muArrRaw[i]
,
for (NSUInteger i = 1; i < [muArrRaw count]; i++) {
for (NSUInteger j = 0; j < [muArrRaw count] - i; j++) {
if ([muArrRaw[j] intValue] > [muArrRaw[j + 1] intValue]) {
// ...
}
}
}
Swapping two elements in the array can be simplified by using the existing method:
[muArrRaw exchangeObjectAtIndex:j withObjectAtIndex:j+1];
If no elements were swapped at all in some pass then the array is already sorted and there is no need to continue:
BOOL swapped;
NSUInteger n = [muArrRaw count];
do {
swapped = NO;
for (NSUInteger j = 0; j + 1 < n; j++) {
if ([muArrRaw[j] intValue] > [muArrRaw[j + 1] intValue]) {
[muArrRaw exchangeObjectAtIndex:j withObjectAtIndex:j+1];
swapped = YES;
}
}
n--;
} while (swapped);
Your method is limited to arrays of integers. If you compare two array elements with
if ([muArrRaw[j] compare:muArrRaw[j+1]] == NSOrderedDescending) { ... }
instead then it applies to all element types which have a compare:
method (e.g. NSNumber
, NSString
, NSDate
...).
Even more general, you can add a comparator argument, as suggested in this answer: