给定一个大小为n的未排序数组,其中包含id为0 ... n-1的对象,并按行和线性时间对数组进行排序。假设对象包含大型成员(如二进制数据),因此实例化对象的新副本非常昂贵。
void linearSort(int* input, const int n) {
for (int i = 0; i < n; i++) {
while (input[i] != i) {
// swap
int swapPoint = input[i];
input[i] = input[swapPoint];
input[swapPoint] = swapPoint;
}
}
}
这是线性的吗?这种排序适用于任何类型的整数?如果是这样,为什么我们需要快速配送呢?
答案 0 :(得分:2)
尽管while
中有for
循环,但这种排序是线性O(n)
。如果while循环对于给定的i
多次出现,那么对于匹配i
的{{1}}值,则根本不会执行while循环。
此实现仅适用于没有重复且整数从0到n-1的整数数组,这就是为什么Quicksort仍然与swapPoint
相关,因为它适用于非顺序值
这可以通过最坏的情况轻松测试:
O(n log n)
然后使用以下代码:
input = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
输出如下:
int whileCount = 0;
for (int i = 0; i < n; i++)
{
while (input[i] != i)
{
whileCount++;
// swap
int swapPoint = input[i];
input[i] = input[swapPoint];
input[swapPoint] = swapPoint;
}
Console.WriteLine("for: {0}, while: {1}", i, whileCount);
}
因此,即使在for: 0, while: 9
for: 1, while: 9
for: 2, while: 9
for: 3, while: 9
for: 4, while: 9
for: 5, while: 9
for: 6, while: 9
for: 7, while: 9
for: 8, while: 9
for: 9, while: 9
循环的第一次迭代中,while
循环运行n-1
次,最糟糕的情况下,您仍然只能获得for
整个过程的while循环迭代。
随机数据的进一步示例:
n-1
答案 1 :(得分:0)
每个人都将input[i]
放到swapPoint
位置,这正是它需要去的地方。因此,在以下步骤中,这些元素已经在正确的位置,交换的总时间不会超过n
的大小。