学习数据结构和算法的第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)

相关推荐
泯泷14 小时前
别再“裸聊”大模型了!你家的 AI 为什么总胡说八道?根子在 RAG
人工智能·算法·架构
fly_sunnn15 小时前
机械狗的前置学习(python与Linux基础操作)
学习
2601_9679801115 小时前
Python中heapq模块的各种用法实例
数据结构·python·算法·应用实例·heapq模块
zaizai100716 小时前
算法(左程云)2
数据结构
漂流瓶jz16 小时前
UVA-1615 高速公路 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·贪心算法·贪心·aoapc·算法竞赛入门经典·uva
Rabitebla17 小时前
【Linux】文件篇(六):Shell 实战——从系统调用到命令行重定向
linux·服务器·c++·笔记·学习
夊17 小时前
数据结构第四课:栈与队列
数据结构
Star(up up up)18 小时前
MySQL 事务隔离级别是如何实现的?从 MVCC 到锁机制原理详解
笔记·vscode·sql·学习·程序人生·mysql·学习方法
凌冰_1 天前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
Pniubi1 天前
力扣2 . 两数相加
算法·leetcode·职场和发展