什麼是冒泡排序法?數組
舒適提示:在理解題意的時候,儘可能能用反向思惟來理解。ide
若有10個大小不1、排序混亂的數字。 若是咱們要將大的排在最前面。spa
咱們能夠經過先將數組中最小的排在後面(這裏的爲了排大的在前面而先排最小的,我就理解爲反向的思惟)。 而後在比較前面9個數字,將最小的拍在第9個位置。 這樣依次類推。直到最後一個。 排序
在這個過程當中其中有一個步驟是將前面的數字進行比較。 這個比較的過程就是一個冒泡的過程。string
若是咱們只有3個數字 1,2,3。 經過冒泡排序法是這樣的。it
一、將第一位和第二位進行比較,大的排前面小的排後面。就變成了:io
2,1,3 class
二、將第二位和第3爲比較,大的排前面小的排後面。就變成了:sso
2, 3, 1word
三、將第1位和第2爲比較,大的排前面小的排後面。就變成了:
3, 2, 1
經過這些將小的數字忘後冒的排序過程咱們就完成了排序
下面是經過C語言來實現的排序過程
- #include <stdio.h>
- int main() {
- int index = 0, index1 = 0, temp;
- int arrays[] = { 1, 2, 3, 4, 5 };
- int arraysLength = 5, moveCount;
- for (index = 0; index < arraysLength; index++) {
- moveCount = arraysLength - 1;
- for (index1 = 0; index1 < moveCount - index; index1++) {
- if (arrays[index1] < arrays[index1 + 1]) {
- temp = arrays[index1];
- arrays[index1] = arrays[index1 + 1];
- arrays[index1 + 1] = temp;
- }
- }
- }
- for (index = 0; index < arraysLength; index++) {
- printf("%d\n", arrays[index]);
- }
- return 0;
- }
打印結果:
5
4
3
2
1