写个object-c的冒泡排序
时间: 2023-02-20 10:40:32 浏览: 37
这是一个简单的冒泡排序程序:
// 冒泡排序
void bubbleSort(int array[], int length) {
int temp;
for (int i = 0; i < length - 1; i++) {
for (int j = 0; j < length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
相关问题
object-c 快速排序
Objective-C 中的快速排序算法可以使用递归方法来实现。
代码实现示例:
```
-(NSArray *)quickSortArray:(NSArray *)array {
if (array.count <= 1) {
return array;
}
NSInteger pivotIndex = array.count / 2;
NSNumber *pivot = array[pivotIndex];
NSMutableArray *less = [NSMutableArray array];
NSMutableArray *greater = [NSMutableArray array];
for (NSInteger i = 0; i < array.count; i++) {
if (i != pivotIndex) {
NSNumber *number = array[i];
if (number.integerValue < pivot.integerValue) {
[less addObject:number];
} else {
[greater addObject:number];
}
}
}
return [[self quickSortArray:less] arrayByAddingObjectsFromArray:@[pivot]];
return [[self quickSortArray:less] arrayByAddingObjectsFromArray:@[pivot] arrayByAddingObjectsFromArray:[self quickSortArray:greater]];
}
```
在上面的代码中,pivotIndex 变量存储了当前数组的中间位置。然后,使用一个 for 循环把数组中的元素分成两部分:比 pivot 小的元素和比 pivot 大的元素。最后,将这两部分的数组分别递归调用 quickSortArray: 方法进行排序,最后将排序完成的数组合并返回。
object-c排序
Objective-C 是一种面向对象的编程语言,它支持对数组、字典等容器的排序。
下面是一个使用 Objective-C 对数组进行排序的简单代码示例:
```
NSArray *array = @[@3, @1, @4, @1, @5];
NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"Sorted Array: %@", sortedArray);
```
输出结果为:
```
Sorted Array: (
1,
1,
3,
4,
5
)
```
如果需要按照特定顺序排序,可以实现`compare:`方法,然后使用`sortedArrayUsingFunction:context:`方法排序:
```
NSArray *array = @[@3, @1, @4, @1, @5];
NSArray *sortedArray = [array sortedArrayUsingFunction:compareFunction context:nil];
NSLog(@"Sorted Array: %@", sortedArray);
NSInteger compareFunction(id num1, id num2, void *context) {
if ([num1 integerValue] < [num2 integerValue]) {
return NSOrderedAscending;
} else if ([num1 integerValue] > [num2 integerValue]) {
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}
```
输出结果为:
```
Sorted Array: (
1,
1,
3,
4,
5
)
```
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)