冒泡排序 選擇排序

1. 冒泡排序

    冒泡排序的主要思路就是挨個兩兩比較大小,符合條件就交換位置,始終將較大的數放在後面。這樣第一輪比較下來就保證了最大的數被放在了 最後面。

 

#include <stdio.h>

#define N 10

int displayArray(int a[], int n);

int bubbleSort(int a[], int n);

 

int main(void)

{

    int a[N], i;

 

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

    {

         printf("Please input the %d th number:/n", i+1);

         scanf("%d", &a[i]);

     }

 

     printf("Then orginal array is: ");

     displayArray(a, N);

 

      bubbleSort(a, N);

      printf("After sort, the array is: ");

      displayArray(a, N);

 

      return 0;

}

 

int displayArray(int a[], int n)

{

    int i;

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

    {

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

     }

     printf("/n");

     return 0;

}

 

int bubbleSort(int a[], int n)

{

    int i, j, temp;

    for(i = 0; i < n-1; i++)          /* compare cycles */

    {

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

         {

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

              {

                    temp = a[j];

                    a[j] = a[j+1];      /* exchange the two number, put the bigger at the behind */

                    a[j+1] = temp;

               }

          }

      }

    return 0;

}

 

2. 選擇排序

    選擇排序的主要思路就是每一輪從“所有備選的數中”選出最小的那一個放在欲排序的位置上,比如:第一輪選出這N個數中最小的一個(假設這個數在數組中的位置是i),將a[0]與a[i]位置互換,這樣最小的就在位置0上了;下一輪接着從a[1]開始挑出剩餘的N-1個數中最小的數與a[1]交換;如此循環下去即可。

 

#include <stdio.h>

#define N 10

int displayArray(int a[], int n);

int selectionSort(int a[], int n);

 

int main()

{

    int a[N];

 

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

    {

         printf("Please input the %d th number:/n", i+1);

         scanf("%d", &a[i]);

     }

 

     printf("Then orginal array is: ");

     displayArray(a, N);

 

      selectionSort(a, N);

      printf("After sort, the array is: ");

      displayArray(a, N);

 

      return 0;

}

 

int displayArray(int a[], int n)

{

    int i;

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

    {

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

     }

     printf("/n");

     return 0;

}

 

int selectionSort(int a[], int n)

{

    int i, j, minIndex, temp;

 

    for(i = 0; i < n-1; i++)                       /* compare cycles */

    {

         minIndex = i;

         for(j = i+1; j < n; j++)

         {

              if(a[minIndex] > a[j])

                  minIndex = j;                     /* record the index of the minimal in array */

         }

 

         temp = a[i];

         a[i] = a[minIndex];                    /* exchange the minimal and a[i] */

         a[minIndex] = temp;

     }

 

     return 0;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章