冒泡排序 选择排序

来源:互联网 发布:java 企业 短信 平台 编辑:程序博客网 时间:2024/04/30 02:34

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;

}

原创粉丝点击