TABLE OF CONTENTS
00:00:00 - Introduction
一种统计班上人数的方法,全部站起来,两两配对,一个坐下,循环
00:01:01 - Overview
00:02:58 - Attendance
00:09:40 - Linear Search
00:24:58 - Binary Search 二分搜索
分而治之的方法
00:28:25 - Running Time
代表这些算法的效率
使用的算法将被描述为这些运动时间之一的数量级
大O代表可能计算步数的上限,考虑的是最坏的情况
O(1)代表恒定的步数,恒定时间算法
O(n) 线性搜索,一页一页翻书
O(n2) n个人与其他所有人握手
00:38:06 - search.c
#include <stdio.h>
#include <cs50.h>
#include <string.h>int main() {string str[] = {"apple", "tree", "dog", "cat", "captital", "aoxue"};string n = get_string("input a string:");for (int i = 0; i < 6; i++) {if(strcmp(str[i], n) == 0) {printf("found\n");return 0;}}printf("not found\n");return 1;
}
00:51:29 - phonebook.c
#include <stdio.h>
#include <cs50.h>
#include <string.h>int main(void) {string names[] = {"dc", "aoxue", "bubu", "pikaqiu"};string numbers[] = {"1818198", "11333","4343455", "5465356"};string n = get_string("input a name:");for (int i = 0; i< 4; i++) {if (strcmp(names[i], n) == 0) {printf("found %s\n", numbers[i]);return 0;}}printf("not found\n");return 1;}
即使在英语中被称为数字,也应该用字符串存储
显然以上这样的code smell不对,不应该将名字和数字分开
00:53:42 - Structs
typedef意味着定义以下数据类型,我要发明这个数据类型
#include <stdio.h>
#include <cs50.h>
#include <string.h>typedef struct {string name;string number;
}person;
int main(void) {// person people[3];// people[0].name = "dc";// people[0].number = "1919191";// people[1].name = "aoxue";// people[1].number = "423423";// people[2].name = "bubu";// people[2].number = "534543";person people[3] = {{"dc", "1919191"},{"aoxue", "423423"},{"bubu", "534543"}};string n = get_string("input a name:");for (int i = 0; i< 3; i++) {if (strcmp(people[i].name, n) == 0) {printf("found %s\n", people[i].number);return 0;}}printf("not found\n");return 1;}
01:05:26 - Sorting
每次都检查整个列表,选择最小元素
01:12:43 - Selection Sort
脑子一次只记得一个元素
01:24:50 - Bubble Sort 冒泡排序
一次次比较邻接关系
01:33:10 - Recursion 递归
该搜索函数正在调用自身,只要有终止条件(基本情况),可以打破无限循环
是对调用自身的函数的描述
iterration.c
#include <stdio.h>
#include <cs50.h>void draw(int n);int main() {int height = get_int("input the height:");draw(height);}void draw(int n) {for (int i = 0; i < n; i++) {for (int j =0; j < i+1; j++) {printf("*");}printf("\n");}
}
recursion.c
#include <stdio.h>
#include <cs50.h>void draw(int n);int main() {int height = get_int("input he height:");draw(height);
}void draw(int n) {if(n <= 0) {return;}draw(n - 1);for (int i = 0; i < n; i++) {printf("*");}printf("\n");
}
01:46:28 - Merge Sort 合并排序
选择排序和冒泡排序只允许自己使用恒定的内存,在计算机科学中,可以用一种资源换另一种资源,想节约时间,就扩展空间
02:00:23 - Sort Race