2013-03-05 42 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]];