【数据结构】详解算法的复杂度

10 篇文章 2 订阅

二、时间复杂度

2.1、时间复杂度的定义

void Func1(int N)
{
int count = 0;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
count++;
}
}
for (int k = 0; k < 2 * N; k++)
{
count++;
}
int M = 10;
while (M--)
{
count++;
}
printf("%d\n", count);
}


Func1执行的基本操作次数：F(N) = N^2+2*N+10

2.2、如何计算时间复杂度

void Func2(int N)
{
int count = 0;
for (int k = 0; k < 2 * N; k++)
{
count++;
}
int M = 10;
while (M--)
{
count++;
}
printf("%d\n", count);
}


void Func3(int N, int M)
{
int count = 0;
for (int k = 0; k < M; k++)
{
count++;
}
for (int k = 0; k < N; k++)
{
count++;
}
printf("%d\n", count);
}


void Func4(int N)
{
int count = 0;
for (int k = 0; k < 100; k++)
{
count++;
}
printf("%d\n", count);
}


const char* strchr(const char* str, int character);


void BubbleSort(int* a, int n)
{
assert(a);
for (size_t end = n; end > 0; end--)
{
int exchange = 0;
for (size_t i = 1; i < end; i++)
{
if (a[i - 1] > a[i])
{
Swap(&a[i - 1], &a[i]);
exchange = 1;
}
}
if (exchange == 0)
break;
}
}


void BinarySearch(int* a, int n,int x)
{
assert(a);
int begin = 0;
int end = n - 1;
while (begin <= end)
{
int mid = begin + ((end - begin) >> 1);
if (a[mid] < x)
begin = mid + 1;
else if (a[mid] > x)
end = mid - 1;
else
return mid;
}
return -1;
}


N=122*2…*2，
N=2 ^ X，
x=logN

long long Fac(size_t N)
{
if (0 == N)
return 1;
return Fac(N - 1) * N;
}


long long Fac(size_t N)
{
if (0 == N)
return 1;
for (size_t i = 0; i < N; i++)
{
;
}
return Fac(N - 1) * N;
}


三、空间复杂度

3.2、如何计算时间复杂度

void BubbleSort(int* a, int n)
{
assert(a);
for (size_t end = n; end > 0; end--)
{
int exchange = 0;
for (size_t i = 1; i < end; i++)
{
if (a[i - 1] > a[i])
{
Swap(&a[i - 1], &a[i]);
exchange = 1;
}
}
if (exchange == 0)
break;
}
}


long long* Fibonacci(size_t n)
{
if (n == 0)
return NULL;
long long* fibArray = (long long*)malloc(n + 1) * sizeof(long long);
fibArray[0] = 0;
fibArray[1] = 1;
for (int i = 2; i <= n; i++)
{
fibArray[i] = fibArray[i - 1] + fibArray[i - 2];
}
return fibArray;
}


s实例3：

long long Fac(size_t N)
{
if (N == 0)
return 1;
return Fac(N - 1) * N;
}


四、常见几种复杂度对比

 123456 O(1) 常数阶 3n+4 O(n) 线性阶 3n^2+4n+5 O(n^2) 平方阶 3logN+4 O(logN) 对数阶 2n+3nlogN+14 O(nlogN) nlogN阶 n ^ 3+2n ^ 2+4n+6 O(n^3) 立方阶 2^n O(2^n) 指数阶
11-23 3万+
04-11 2215
03-25 1908
09-27 1万+
08-06 1014
09-28 367
03-08 2776
12-27 1825
03-24 1986
01-04 7122

¥1 ¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。