用OC写一个冒泡排序
时间: 2023-03-02 10:32:29 浏览: 135
以下是使用 Objective-C 语言实现冒泡排序的示例代码:
```objc
- (NSArray *)bubbleSort:(NSArray *)unsortedArray {
NSMutableArray *sortedArray = [unsortedArray mutableCopy];
NSInteger count = sortedArray.count;
BOOL swapped = NO;
do {
swapped = NO;
for (NSInteger i = 1; i < count; i++) {
if ([sortedArray[i-1] compare:sortedArray[i]] == NSOrderedDescending) {
[sortedArray exchangeObjectAtIndex:i withObjectAtIndex:i-1];
swapped = YES;
}
}
count--;
} while (swapped);
return sortedArray;
}
```
在这个实现中,我们使用 `NSMutableArray` 来存储输入的未排序数组。我们使用一个布尔变量 `swapped` 来记录在一次遍历中是否有元素交换的操作,如果没有发生任何交换,说明数组已经排序完成,排序过程可以结束。
在每一次遍历中,我们比较相邻的两个元素,如果它们的顺序不正确(按升序排列),就交换它们的位置,并将 `swapped` 标记为 `YES`。当一次遍历结束后,我们减少待比较的元素的个数 `count`,因为在上一次遍历中,最后的 `count` 个元素已经排序好了。
最终,我们将排序好的 `NSMutableArray` 转换为 `NSArray` 并返回。
阅读全文
相关推荐















