我有一个数组
@["A","B","C","D","E","F","G"]
我想像下面这样交叉排序
@["A","G","B","F","C","E","D"]
使最后一个项目每 2 次滑到前面。
我有一个数组
@["A","B","C","D","E","F","G"]
我想像下面这样交叉排序
@["A","G","B","F","C","E","D"]
使最后一个项目每 2 次滑到前面。
我看你什么都没试过。如果是因为您还没有找到任何算法,或者您想不出一个算法,那么这段代码可能会有所帮助:
@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);
}
这可以这样做:
将数组分成两半。
对它们进行排序。
再次合并它们以形成您的结果。在这里您需要迭代替代方案,即 step+=2
编辑:运行代码如下
NSArray *array=@[@"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);
您可以使用一个简单的循环来完成,将对象添加到输出数组中;
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]];