我想在数组下面排序,我只能交换两个元素。
示例:
NSArray *arr = @[@10, @20, @60, @40, @50, @30];
// 30 and 60 are swapped
Output: 10, 20, 30, 40, 50, 60
请在Objective c或Swift中回答。 提前谢谢!
答案 0 :(得分:1)
使用以下exchangeObject功能是正确的方法。
NSArray *arr = @[@10, @20, @60, @40, @50, @30];
int n = (int)arr.count;
NSMutableArray *arrm = [arr mutableCopy];
for (int i = n-1; i > 0; i--)
{
// Check if arrm[i] is not in order
if (arrm[i] < arrm[i-1])
{
// Find the other element to be
// swapped with arr[i]
int j = i-1;
while (j>=0 && arrm[i] < arrm[j])
j--;
// Swap the pair
[arrm exchangeObjectAtIndex:i withObjectAtIndex:j+1];
break;
}
}
NSLog(@"Given array is :%@",arr);
NSLog(@"Sorted array is :%@",arrm);
祝你好运!