Loops - for
Wu-Jun Pei
Loops? 迴圈?
Yahoo 字典:(線,鐵絲等繞成的)圈,環
Loop
Loops can...
Do something similar again and again and again and again........
試想如果你要計算 2 + 4 + 6 + 8 + .... + 98 + 100
你可以
int sum = 2 + 4 + 6 + ... + 100;難道當工程師只能這樣慢慢加,一個求和問題就要自己打到天荒地老,這小學生都會(?
這個時候聰明的你們一定會嘲笑講師沒有國高中數學能力
sum = \mathop{\sum_{i=1}^{50} } 2*{i}
sum=∑i=1502∗i
= 2 * [ (50)*(50+1)/2 ]
=2∗[(50)∗(50+1)/2]
= 2550
=2550
如果有複雜的問題呢
- 1-1000之中
- 是 2, 5, 11, 17 的倍數但不是 3, 7, 13 的倍數的和
如果有複雜的問題呢
- 難道又要用各種排容和按不完的計算機解決問題嗎
試試看新一代卡西歐計算機(X
試試看For 吧(O
for (initialization; condition; variable update) {
//do something until the condition becomes false
}Loop
For - Example
for (int i = 0; i <= 100; i++) {
//do something until i > 100
}For - Example
Sum of even numbers from 1 - 100
int cnt = 0;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
cnt += i;
}
}
std::cout << cnt << std::endl;For - Example
Sum of even numbers from 1 - 100
int cnt = 0;
for (int i = 2; i <= 100; i += 2) {
cnt += i;
}
std::cout << cnt << std::endl;For - Example
常見的錯誤
for (int i = 0, i <= 100, i++) {
//do something until i > 100
}For - Example
常見的錯誤
for (int i = 0; i <= 100; i++) {
//do something until i > 100
}Practice
- 1-1000之中
- 是 2, 5, 11, 17 的倍數但不是 3, 7, 13 的倍數的和
Sort
什麼時候會用到 sort(排序)
- 打撲克牌的時候,如果你有理牌的習慣
- 打麻將的時候,如果你沒有盲打的習慣
- 各種排序問題,像是按照身高排隊
- 排序是許多演算法的基礎,如二分搜
How to sort
- Bubble Sort
- Selection Sort
- Insertion Sort
- ......
Bubble Sort
- Idea: 對於兩兩相鄰的元素,把比較大的放到右邊,執行(一輪)一次迴圈後,最大的就被換到最右邊了!接下來就可以換第二大、第三大......最後的序列會被排序好!
Bubble Sort
void bubble_sort (int arr[], int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[ j ] > arr[ j + 1 ]) {
std::swap(arr[ j ], arr[ j + 1 ]);
}
}
}
}Bubble Sort
短短幾行就完成sort了!
還不快試試看!
Selection Sort
- Idea: 每次找原本陣列最小的,把它拿出來,再把他丟到新的陣列中,之後看第二小的,直到原本陣列為空,則新的陣列將會是排序好的序列。
Insertion Sort
- Idea: 陣列可分為兩部分,左半為已排序的,右半為為排序的部分。每次將右半部的第一個元素插到左半部它該在的位子,則左半將一直維持排序,最後整個序列會被排序好。
什麼!還不夠!
STL的 std::sort
std::sort( arr, arr+n );Q&A
Loops-For
By Wu-Jun Pei
Loops-For
- 33