120 likes | 211 Views
Bubble sort, also known as sinking sort, gradually sorts an array by repeatedly stepping through the list, comparing each pair of adjacent items, and swapping them if they are in the wrong order. The largest values "bubble up" to the end of the list. In this algorithm, the largest element is progressively moved to its correct position. By understanding the process of bubbling up the largest element, you can grasp the fundamental sorting technique.
E N D
Bubble Sort • 也稱之為冒泡排序法 • 就像泡泡一樣,最大的數值會往尾端移動,最小的數值會往前端移動。
35 12 77 101 5 42 Sorting • Sorting takes an unordered collection and makes it an ordered one. 1 2 3 4 5 6 101 12 42 35 5 77 1 2 3 4 5 6
"Bubbling Up" the Largest Element • Traverse a collection of elements • Move from the front to the end • “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 101 12 42 35 5 77
42 77 "Bubbling Up" the Largest Element • Traverse a collection of elements • Move from the front to the end • “Bubble” the largest value to the end using pair-wise comparisons and swapping Swap 1 2 3 4 5 6 101 12 42 35 5 77
35 77 "Bubbling Up" the Largest Element • Traverse a collection of elements • Move from the front to the end • “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 Swap 101 12 77 35 5 42
12 77 "Bubbling Up" the Largest Element • Traverse a collection of elements • Move from the front to the end • “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 Swap 101 12 35 77 5 42
"Bubbling Up" the Largest Element • Traverse a collection of elements • Move from the front to the end • “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 101 77 35 12 5 42 No need to swap
5 101 "Bubbling Up" the Largest Element • Traverse a collection of elements • Move from the front to the end • “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 Swap 101 77 35 12 5 42
"Bubbling Up" the Largest Element • Traverse a collection of elements • Move from the front to the end • “Bubble” the largest value to the end using pair-wise comparisons and swapping 1 2 3 4 5 6 101 5 77 35 12 42 Largest value correctly placed
(1)比較相鄰的兩個元素,若前面的元素較大就進行交換。(1)比較相鄰的兩個元素,若前面的元素較大就進行交換。 • (2)重複進行(1)的動作直到最後面,最後一個元素將會是最大值。 • 重複進行(1),(2)的動作,每次比較到上一輪的最後一個元素。