当前位置:网站首页>bubble sort

bubble sort

2022-06-23 03:45:00 @Landscape post yuan

The structures and functions used in sorting

# define MAXSIZE 10
 typedef struct {
     /*  use   On   save   Store   want   row   order   Count   Group  , r[0]  use   do   whistle   The soldiers   or   In the   when   change   The amount  */
     int r[ MAXSIZE + 1];
     /*  use   On   remember   record   along   order   surface   Of   Long   degree  */
     int length ;
 } SqList ;
 /*  hand over   in  L  in   Count   Group  r  Of   Next   mark   by  i  and  j  Of   value  */
 void swap ( SqList *L, int i, int j){
     int temp = L- >r[i];
     L->r[i] = L- >r[j];
     L->r[j] = temp ;
 }

Bubble sort primary version

/*  Yes   along   order   surface  L  do   hand over   in   row   order  (  Risk   bubble   row   order   first   level   edition  ) */
 void BubbleSort0 ( SqList *L){
 int i, j;
 for (i = 1; i < L- > length ; i++) {
     for (j = i + 1; j <= L- > length ; j++) {
         if (L- >r[i] > L->r[j]) {
             /*  hand over   in L- >r[i]  And L->r[j]  Of   value  */
             swap (L, i, j) ;
             }
         }
     }
 }

Bubble sort classic version —— Two by two

/*  Yes   along   order   surface  L  do   Risk   bubble   row   order  */
 void BubbleSort ( SqList *L){
 int i, j;
 for (i = 1; i < L- > length ; i++) {
     /*  notes   It means  j  yes   from   after   Go to   front   Follow   Ring  */
     for (j = L-> length - 1; j >= i;j - -) {
     /*  if   front   person   Big   On   after   person  (  notes   It means   this   in   And   On   One   count   Law   Bad   different  ) */
         if (L- >r[j] > L->r[j + 1]) {
             /*  hand over   in L- >r[j]  And L->r[j+1]  Of   value  */
             swap (L, j, j + 1) ;
             }
         }
     }
 }

Bubble sort upgrade version

If the embedded inner loop does not need to be swapped , So it means that the initial values of the following sequence are arranged

void BubbleSort2 ( SqList *L){
 int i, j;
 Status flag = TRUE ; /* flag  use   Come on   do   by   mark   remember  */
 /*  if  flag  by  true  say   bright   Yes   too   Count   According to the   hand over   in  ,  no   be   stop   stop   Follow   Ring  */
 for (i = 1; i < L- > length && flag ; i++) {
     flag = FALSE ;/*  first   beginning   by  false */
     for (j = L-> length - 1; j >= i; j - -) {
         if (L- >r[j] > L->r[j + 1]) {
             /*  hand over   in L- >r[j]  And L->r[j+1]  Of   value  */
             swap (L, j, j + 1) ;
             /*  Such as   fruit   Yes   Count   According to the   hand over   in  ,  be  flag  by  true */
             flag = TRUE ;
             }
         }
     }
 }

原网站

版权声明
本文为[@Landscape post yuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206222235485985.html