2013-03-05 41 views
-4

我有一个数组NSArray的排序十字交叉

@ [ “A”, “B”, “C”, “d”, “E”, “F”, “G”]

,我想对它进行排序的十字交叉状以下

@ [ “A”, “G”, “B”, “F”, “C”, “E”, “d”]

这样最后的项目每2次滑动一次 前方。

+0

试过了吗? – trojanfoe 2013-03-05 16:30:30

回答

4

我看你有没有尝试过任何东西。如果是因为你还没有找到任何算法,或者想不通一个在你的心中,这个代码可能会有所帮助:

@autoreleasepool 
{ 
    BOOL tail= NO; // To know if you should remove from array's tail or head. 
    NSMutableArray* array=[NSMutableArray arrayWithArray: @[@"A",@"B",@"C",@"D",@"E",@"F",@"G"] ]; // The unsorted array. 
    // This will contain sorted objects: 
    NSMutableArray* sorted=[[NSMutableArray alloc]initWithCapacity: array.count]; 
    // The algorithm will end when array will be empty: 
    while(array.count) 
    { 
     NSUInteger index= tail? array.count-1:0; // I decide the index of the object 
               // to remove. 
     // The removed object will be added to the sorted array, so that it will 
     // contain the object on head, then on tail, then again on head, and so on... 
     id object= array[index]; 
     [sorted addObject: object]; 
     [array removeObjectAtIndex: index]; 
     tail= !tail; 
    } 
    NSLog(@"%@",sorted); 
} 
+1

优雅的解决方案 – mozillanerd 2013-03-05 16:59:24

3

可以这样做:

将数组分成两半。

对它们进行排序。

再次合并它们以形成您的结果。在这里,你需要遍历替代,I,E步+ = 2

编辑:正在运行的代码如下

NSArray *[email protected][@"A",@"B",@"C",@"D",@"E",@"F",@"G"]; 
NSArray *halfLeft=[array subarrayWithRange:NSMakeRange(0, array.count/2+1)]; 
NSMutableArray *halfRight=[NSMutableArray arrayWithArray:array]; 
[halfRight removeObjectsInArray:halfLeft]; 
NSMutableArray *finalAray=[[NSMutableArray alloc]initWithArray:halfLeft]; 
for (NSInteger i=0, index=1; i<halfRight.count; i++, index+=2) { 
    [finalAray insertObject:halfRight[halfRight.count-1-i] atIndex:index]; 
} 
NSLog(@"%@",finalAray); 
0

你可以用一个简单的循环做到这一点,将对象添加到输出数组你走;

NSArray *input = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H"]; 
NSMutableArray *output = [[NSMutableArray alloc] init]; 

// Quickly add all except possibly the middle one, makes the loop simple 
for(int i=0; i<input.count/2; i++) 
{ 
    [output addObject:input[i]]; 
    [output addObject:input[input.count-i-1]]; 
} 

// If there is an odd number of items, just add the last one separately 
if(input.count%2) 
    [output addObject:input[input.count/2]];