使用数组和指针的形式实现冒泡排序,并优化。bubble_sort();


方法一:

#define CRT_SECURE_NO_WARNINGS 1

#include

#include

#include

 

int main()

{

         intp[10]={5,4,7,1,9,3,8,2,6,0}; 

         inti=0;

         intj=0;

         for(i=0;i<10;i++)

         {                   

       for(j=0;j<(10-i-1);j++)

                   {              

           if(p[j]>p[j+1])

                            {            

                int temp=p[j];

                p[j]=p[j+1];

                p[j+1]=temp;     

           } 

        }  

         }

   printf("数组按升序排后:\n"); 

   for(i=0;i<10;i++)

         {   

       printf("%d ",p[i]); 

   } 

         system("pause");

   return 0;

 

}

方法二:(数组)

#define CRT_SECURE_NO_WARNINGS 1

#include

#include

#include

void bubble_sort(int arr[],int sz)

{

    int i=0;

    int j=0;

    //int sz=sizeof(arr)/sizeof(arr[0]);

    for ( i = 0; i < sz-1; i++)

    {

          for ( j = 0;j

         {

               int temp=0;

               if (arr[j]

               {

                    temp = arr[j];

                    arr[j] = arr[j+1];

                    arr[j+1] = temp;

               }

                //printf("%d  ",arr[j]);

          }

    }

}

 

int main()

{

     int x[] = { 5,3,9,0,7,8,4,1,2};

     int k=0;

     int sz=sizeof(x)/sizeof(x[0]);

     printf("排序后\n");

     bubble_sort(x,sz);

 

     for(k=0;k

     {

         printf("%d  ",x[k]);

     }

    system("pause");

    return 0;

}

方法三:(指针)

#define CRT_SECURE_NO_WARNINGS 1

#include

#include

#include

void bubble_sort(int arr[],int sz)

{

         inti=0;

         intj=0;

         //intsz=sizeof(arr)/sizeof(arr[0]);

   for ( i = 0; i < sz-1; i++)

    {

          for ( j = 0;j

        {

                               int temp=0;

               if (*(arr+j) <*(arr+j+1))

                {

                     temp =*(arr+j);

                     *(arr+j)=*(arr+j+1);

                    *(arr+j+1) = temp;

                }

                                //printf("%d  ",arr[j]);

                     }

    }

}

 

int main()

{

    int x[] = {3,8,77,5,10,24,9,35,89 };

          int k=0;

          int sz=sizeof(x)/sizeof(x[0]);

          printf("排序后\n");

          bubble_sort(x,sz);

 

          for(k=0;k

          {

                    printf("%d  ",x[k]);

          }

         system("pause");

         return0;

}

你可能感兴趣的:(C语言)