C語言排序之冒泡排序法

 什麼是冒泡排序法?數組

    舒適提示:在理解題意的時候,儘可能能用反向思惟來理解。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語言來實現的排序過程

  
  
  
  
  1. #include <stdio.h> 
  2.  
  3. int main() { 
  4.     int index = 0, index1 = 0, temp; 
  5.     int arrays[] = { 1, 2, 3, 4, 5 }; 
  6.     int arraysLength = 5, moveCount; 
  7.     for (index = 0; index < arraysLength; index++) { 
  8.         moveCount = arraysLength - 1; 
  9.         for (index1 = 0; index1 < moveCount - index; index1++) { 
  10.             if (arrays[index1] < arrays[index1 + 1]) { 
  11.                 temp = arrays[index1]; 
  12.                 arrays[index1] = arrays[index1 + 1]; 
  13.                 arrays[index1 + 1] = temp; 
  14.             } 
  15.         } 
  16.     } 
  17.     for (index = 0; index < arraysLength; index++) { 
  18.         printf("%d\n", arrays[index]); 
  19.     } 
  20.     return 0; 

打印結果:

5

4

3

2

1    

相關文章
相關標籤/搜索