[Swift Algorithm] Bubble sort
2016-07-16 本文已影响63人
sunlitamo
Swift
func bubbleSort(src: inout [Int]) {
let count = src.count
for i in 0 ..< count {
for j in 1 ..< count - i {
if src[j - 1] < src[j] { swap(&src[j - 1], &src[j]) }
}
}
}
Objective-C
NSMutableArray* bubbleSort(NSMutableArray *arr)
{
BOOL swapped = YES;
int k = 0;
while (swapped) {
swapped = NO;
for (int i = 0; i < arr.count - 1 - k; i++) {
if ([arr objectAtIndex:i] > [[arr objectAtIndex:i + 1]) {
[arr exchangeObjectAtIndex:i withObjectAtIndex:i + 1];
swapped = YES;
}
}
k++;
}
return arr;
}