水一篇博客
时间复杂度与空间复杂度计算>>>
#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include<stdio.h>
#include<stdlib.h>
//——————分割线——————
//阶乘算法>>>这个算法很挫,时间复杂度->O(2^N);
//long long Fibonacci_r(size_t N)
//{
// return N < 2 ? N : Fibonacci_r(N - 1) + Fibonacci_r(N - 2);
//}
//int main()
//{
// int n = 0;
// scanf("%d", &n);
// printf("%lld\n", Fibonacci_r(n));
// return 0;
//}
//优化算法>>>以空间换时间>>>时间复杂度->O(N);
#define MALLOC(num, type) ((type*)malloc(num * sizeof(type)))
long long* Fibonacci(size_t N)
{
long long* FibArray = MALLOC((N + 1), long long);// 自定义宏开辟内存谨慎使用,容易导致内存泄漏!!!
FibArray[0] = 0;
if (N == 0)
{
return FibArray;
}
FibArray[1] = 1;
for (int i = 2; i <= N; ++i)
{
FibArray[i] = FibArray[i - 1] + FibArray[i - 2];
}
return FibArray;
}
int main()
{
int n = 0;
scanf("%d", &n);
long long* p = Fibonacci(n);
printf("%lld\n", *( p + n));
free(p);
p = NULL;
return 0;
}
//——————分割线——————
// 计算BubbleSort的时间复杂度?
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;
}
}
//最好执行N次
//最坏执行(N*(N+1)/2)次
//时间复杂度->O(N^2)
//——————分割线——————
// 计算BinarySearch的时间复杂度?
int BinarySearch(int* a, int n, int x)
{
assert(a);
int begin = 0;
int end = n;
while (begin < end)
{
int mid = begin + ((end - begin) >> 1);
if (a[mid] < x)
begin = mid + 1;
else if (a[mid] > x)
end = mid;
else
return mid;
}
return -1;
}
//最好1次->O(1)
//最坏>>>
//N/2/2/2/....../2=1->(X个2)
//N=2^X
//X=log(2)N
//->O(logN)->默认以2为底
// 二分查找快是快,但是排序是个问题
//——————分割线——————
如有错误,欢迎指出!