如何对可以交换 Objective-C 中的两个元素的数组进行排序

How to sort an Array where I can swap two elements in Objective-C

我想在只能交换两个元素的数组下方排序。

示例:

NSArray *arr = @[@10, @20, @60, @40, @50, @30];  
// 30 and 60 are swapped
Output: 10, 20, 30, 40, 50, 60

正在 Objective-C 或 Swift 中寻找答案。

使用下面的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);

祝你好运!