学习数据结构和算法的第3天

常数循环的复杂度

计算Func4的时间复杂度

c 复制代码
voidFunc4(int N)
{
int count = 0;
for (int k = 0; k < 100; ++ k)
{
++count;
}
printf("%d\n", count);
}

O(1) 不是代表算法运行一次,是常数次

strchar的时间复杂度

c 复制代码
#include<stdio.h>
void const char*strchr(const char*str,int character);
{
    while(*str)
    {
        if(*str==character)
            return 0;
        else
            ++str;
    }
}

假设查找的是h 1 最好情况:任意输入规模的最小运行次数(下界)

假设查找的是w N/2 平均情况:任意输入规模的期望运行次数

假设查找的是d N 最坏情况:任意输入规模的最大运行次数(上界)

当一个算法随着输入不同,时间复杂度不同,时间复杂度做悲观预期,看最坏的情况

冒泡排序的时间复杂度

计算Bubb1esort的时间复杂度

c 复制代码
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; ++1)
        {
            if (a[1-1]> a[i])
            {
	Swap(&a[1-1], &a[i]);
	exchange = 1;
            }
        }
	if (exchange == 0)
break;
    }
}

精确:F(N)=N(N-1)/2* 一个等差数列

时间复杂度:O(N*2)

时间复杂度不能只看是几层循环,而是要去看它的思想

计算Binarysearch的时间复杂度:

c 复制代码
int Binarysearch(int* a, int n, int x)
{
    assert(a);
	int begin= 0;
	int end = nl;
	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;
}

F(N)=O(logN)

相关推荐
BK贝壳1 小时前
初始化一亿个全 True 或全 False:bool-hybrid-array 的 TruesArray/FalsesArray 占位构造本机实测
开发语言·数据结构·python·性能优化·numpy
郝学胜-神的一滴2 小时前
Effective STL 条款 17:用 swap 技巧去掉多余容量
c语言·开发语言·数据结构·c++·算法·rpc
玩转单片机与嵌入式2 小时前
深入浅出TinyML 36:如何验证一个TinyML系统真正具备工程应用价值?
网络·人工智能·算法
蓝祁子yoky2 小时前
QML学习日记 Day9:多媒体
学习
傲世仙尊3 小时前
环形链表找入环点-从相遇到等距的最后一推
数据结构·链表
Nazarick4 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴4 小时前
斐波那契数列题解
算法·leetcode
郝学胜-神的一滴5 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Keven_116 小时前
算法札记:有限差分
算法
忙里偷闲学python6 小时前
GK2A 林火蔓延预报算法说明
算法