杂乱数组的奇偶数分类
问题描述
将一个奇偶数都有的数列分类整理,前面是奇数,后面是偶数。
解决方法
对于算法很烂的我,总是会把自己绕进去,然后发现需要修补的问题会越来越多,代码也是越来越多,越来越杂乱,最后还很可能不正确。
问题还是要分析透彻的,不要一上来就写代码,我们先来描述一下解决这个问题的算法。首先设置两个指针,第一个指针从头开始用来寻找偶数;第二个指针从尾部开始,用来寻找奇数,找到后进行数据交换;第一个指针总是在第二个指针前面,每个指针通过循环进行移动,当两个指针相遇的时候,这个数组的奇偶数就已经分类好了。下面贴代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| #import <Foundation/Foundation.h> int main(int argc, const charchar * argv[]) { @autoreleasepool { NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:@5 ,@3 ,@2 ,@4 ,@1 ,@6 ,@7 ,@1 ,@8 ,@0 ,nil]; NSInteger i=0; NSInteger j=arr.count-1; int tmp = 0; while (i<j) { if ([[arr objectAtIndex:i] intValue]%2 !=0) { i++; continue; } if ([[arr objectAtIndex:j] intValue]%2 ==0 ) { j--; continue; } tmp = [[arr objectAtIndex:i] intValue]; [arr replaceObjectAtIndex:i withObject:[arr objectAtIndex:j]]; [arr replaceObjectAtIndex:j withObject:[NSNumber numberWithInt:tmp]]; } NSLog(@"%@",arr); } return 0; }
|