演算法 Algorithm
演算法的運作時間(步數)
O = 算法的時間上限
Ω = 算法的時間下限
θ = 算法上限 == 算法下限
ex. O(n^2), O(n), O(log n), O(1)
搜尋 Search
線性搜尋法 Linear Search => O(n)、Ω(1)
for each door from left to right
if nubere is behind door
return true
else
return false
二分搜尋法 Binary Search => O(log n)、Ω(1)
if no doors
return false
if number behind middle door
return true
else if number < middle door
search left half
else if number > middle door
search right half
排序 Sort
選擇排序 Selection Sort => ~θ(n^2)
=> comparing sort
for i from 0 to n-1
find smallest number between numbers[i] and numbers[n-1]
swap smallest number between numbers[i]
泡沫排序 Bubble Sort => ~O(n^2)、Ω(n-1)
=> comparing sort
repeat n-1 times
for i from 0 to n-2
if numbers[i] and numbers[i+1] out of order
swap them
合併排序 Merge Sort => θ(log n)
=> recursion sort
If only one number
quit
Else
Sort left half of numbers
Sort right half of numbers
merge sorted halves
Data Structure 自定型態
typedef struct
{
string name;
string number;
}
person;
int main(void)
{
person people;
people[0].name = "Penny";
people[0].number = "1995";
people[1].name = "Leo";
people[1].number = "1996";
for (int i = 0; i < 2; i++)
{
if(strcmp(peolple[i].name) == 0)
{
printf("%s\n", people[i].number);
return 0;
}
}
printf("not found.\n")
return 1;
}
偽代碼 (虛擬代碼) pseudocode
介於自然語言(English)程式語言(code)之間的描述法。
遞迴 Recursion
function that call itself