OC冒泡排序算法
面试的时候很多公司会要求写一个冒泡排序算法,于是用OC写了一个,代码如下所示
需要注意的事项:oc数组只能存放oc对象,因此遍历数组输出的时候,记得通过NSString对象转换成intValue
#import <Foundation/Foundation.h>
void bubleSort(NSMutableArray *numbers){
int i,j,count= (int)[numbers count];
for (i = 0; i < count; i++) {
for (j = i+1; j<count; j++) {
int a = [[numbers objectAtIndex:i] intValue];
int b = [[numbers objectAtIndex:j] intValue];
if (a>b) { //从小到大
[numbers replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%d",b]];
[numbers replaceObjectAtIndex:j withObject:[NSString stringWithFormat:@"%d",a]];
}
}
}
for (NSString *num in numbers) {
NSLog(@"%d",[num intValue]);
}
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSMutableArray *p = [[NSMutableArray alloc] initWithObjects:@"3",@"6",@"4",@"5",@"1",@"2", nil];
bubleSort(p);
}
return 0;
}
posted on 2015-08-03 17:48 xiaowenhui 阅读(2332) 评论(0) 编辑 收藏 举报