如何证明算法的正确性和运行时间

时间:2014-11-30 19:31:49

标签: algorithm runtime correctness

如何证明算法的正确性和运行时间?

例如,假设我要求证明算法的正确性和运行时间本质上是计算排序..我知道它在最坏的情况下运行O(n),但是idk如何证明正确性或证明运行时为O(n)。

问题:描述一种算法,在O(n)时间内对n个整数进行排序,每个整数的范围为[0..n4 - 1]。证明算法的正确性和运行时间。

工作:

Algorithm to sort n integers in the range [0..(n^4)-1] in O(n)
Use countSort with respect to the least significant digit
    countSort with respect to the next least significant digit

Represent each int x in the list as its 4 digits in base n
let k = (n^4)-1       the max value in the range
Since values range from 0..k,  create k+1 buckets
Iterate through the list and increment counter each time a value appears
Fill input list with the data from the buckets where each key is a value in the list
    From smallest to largest key, add bucket index to the input array

Variables:
    array: list of ints to be sorted
    result: output array (indexes from 0..n-1)
    n: length of the input
    k: value such that all keys are in range 0..k-1
    count: array of ints with indexes 0..k-1 (starts with all = 0)
    x: single input value
    total/oCount: control variables

total=0
for x in array
    count[key of x] ++
for i < length of k-1
    oCount = count[i]
    count[i] = total
    total += oCount
for x in array
    result[count[key of x]] = x
    count[key of x] ++
return result

该算法使用简单循环而不递归。初始化计数数组和计算数组上的和的中间for循环最多迭代k + 1次。 1是常数,因此需要O(k)。循环初始化结果数组和输入数组将花费O(n)时间。这些总计为O(n + k)时间。 k被认为是常数,因此最终运行时间为O(n)

我需要一些帮助才能指出正确的方向。谢谢!

0 个答案:

没有答案