如何使用以下方法对数组进行排序并保留重复项?我想要的只是对距离数组进行排序,并让 lineItems 数组以相同的顺序排序,以便我的订单项按距离排序。是否有捷径可寻?我已经尝试了许多不同的实现,但没有运气。
lineItems = [[NSMutableArray alloc] initWithArray:(NSMutableArray *)[data objectForKey:@"line_items"]];
distanceArray = [[NSMutableArray alloc] initWithCapacity:[lineItems count]];
for (int i = 0; i < [lineItems count]; i++) {
CLLocation *spotLocation = [[CLLocation alloc] initWithLatitude:[[[lineItems objectAtIndex:i] objectForKey:@"latitude"] floatValue] longitude:[[[lineItems objectAtIndex:i] objectForKey:@"longitude"] floatValue]];
CLLocationDistance distance = ([myLocation distanceFromLocation:spotLocation] / 1000) * 0.621371192;
NSNumber *foo = [[NSNumber alloc] initWithDouble:distance];
[distanceArray insertObject:foo atIndex:i];
}
我的冒泡排序实现:
for (int i=0;i<[distanceArray count]-1;i++){
for(int j=1;j<[distanceArray count];j++){
if ([[distanceArray objectAtIndex:i]doubleValue] >[[distanceArray objectAtIndex:j]doubleValue]){
NSNumber *temp_i = [[NSNumber alloc] initWithDouble:[[distanceArray objectAtIndex:i]doubleValue]];
NSNumber *temp_j = [[NSNumber alloc] initWithDouble:[[distanceArray objectAtIndex:j]doubleValue]];
[distanceArray removeObjectAtIndex:i];
[distanceArray removeObjectAtIndex:j];
[distanceArray insertObject:temp_j atIndex:i];
[distanceArray insertObject:temp_i atIndex:j];
NSDictionary *tempObj_i = [[NSDictionary alloc] initWithDictionary:[lineItems objectAtIndex:i]];
NSDictionary *tempObj_j = [[NSDictionary alloc] initWithDictionary:[lineItems objectAtIndex:j]];
[lineItems removeObjectAtIndex:i];
[lineItems removeObjectAtIndex:j];
[lineItems insertObject:tempObj_j atIndex:i];
[lineItems insertObject:tempObj_i atIndex:j];
}
}
}