C程序使用冒泡排序按升序对给定的数字列表进行排序

在 C 编程语言中,冒泡排序是最简单的排序技术,也称为交换排序。

冒泡排序的过程

  • 将第一个元素与列表中的其余元素以及exchange(swap)它们进行比较,如果它们没有顺序。

  • 对列表中的其他元素重复相同的操作,直到所有元素都被排序。

算法

下面给出的是一种使用冒泡排序技术按升序对给定数字列表进行排序的算法 -

步骤 1 - 开始

步骤 2 - Take list(array), num

第 3 步 -readlist(list,num)

第 4 步-printlist(list,num)

第 5 步-bub_sort(list,num)

第 6 步-printlist(list,num)

readlist (list, num)

步骤 7 - 停止

1. for j = 0 to num
2. read list[j].

printlist(list,num)

1. for j =0 to num
2. write list[j].

bub_sort(list,num)

1. for i = 0 to num
2. for j =0 to (num – i)
3. if( list[j] > list[j+1])
4. swapList( address of list[j], address of list[j+1])

swapList(列表[j]的地址,列表[j+1]的地址)

1. temp = value at list[j]
2. value at list[j] = value at list[j+1]
3. value at list[j+1] = temp

示例

以下是使用冒泡排序技术按升序对给定数字列表进行排序的 C 程序-

#include <stdio.h>
#define MAX 10
void swapList(int *m,int *n){
   int temp;
   temp = *m;
   *m = *n;
   *n = temp;
}
/* Function for Bubble Sort */
void bub_sort(int list[], int n){
   int i,j;
   for(i=0;i<(n-1);i++)
      for(j=0;j<(n-(i+1));j++)
         if(list[j] > list[j+1])
            swapList(&list[j],&list[j+1]);
   }
   void readlist(int list[],int n){
   int j;
   printf("\nEnter the elements: \n");
   for(j=0;j<n;j++)
      scanf("%d",&list[j]);
   }
   /* Showing the contents of the list */
   void printlist(int list[],int n){
      int j;
   for(j=0;j<n;j++)
      printf("%d\t",list[j]);
}
void main(){
   int list[MAX], num;
   printf(" Enter the number of elements \n");
   scanf("%d",&num);
   readlist(list,num);
   printf("\n\nElements in the list before sorting are:\n");
   printlist(list,num);
   bub_sort(list,num);
   printf("\n\nElements in the list after sorting are:\n");
   printlist(list,num);
}

输出结果

执行上述程序时,会产生以下结果 -

Enter the number of elements
10

Enter the elements:
11
23
45
1
3

6
35
69
10
22


Elements in the list before sorting are:
11 23 45 1 3 6 35 69 10 22

Elements in the list after sorting are:
1 3 6 10 11 22 23 35 45 69