有序数组@[@1,@5,@7,@9,],插入一个数@[@3],插入后数组还是有序排列,怎么写,我写的这个不对,输出是
1,
5,
7,
9,
3
求解怎么做
- #import <Foundation/Foundation.h>
- int main(int argc, const char * argv[]) {
- @autoreleasepool {
- //定义一个数组
- NSMutableArray *arr1 = [NSMutableArray arrayWithObjects:@"1",@"5",@"7",@"9",nil];
-
- //打印数组
- NSLog(@"arr1 = %@",arr1);
-
- //添加数组元素
- [arr1 addObject:@"3"];
-
- //定义一个字符串变量temp
- NSString *temp;
-
- //用冒泡排序从小到大将数组里的元素进行排序
- for (int i = 0; i<[arr1 count] - 1; i++)
- {
- for (int j = 0; j<[arr1 count]-i-1;j++)
- {
- if (arr1[j]>arr1[j+1])
- {
-
- temp = arr1[j];
- arr1[j] = arr1[j+1];
- arr1[j+1] = temp;
-
- }
- }
- }
-
- NSLog(@"arr1 = %@",arr1);
-
- }
- return 0;
- }
复制代码 |
|