
在 C 编程语言中,冒泡排序是最简单的排序技术,也称为交换排序。
冒泡排序过程
算法
下面给出的是一种算法,通过使用冒泡排序技术 -
第 1 步 - 开始
第 2 步 - 获取列表(数组),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].
打印列表(列表,数字)
1. for j =0 to num
2. write list[j].
bub_sort(列表,数字)
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( list[j]的地址, list[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("Enter the elements:
");
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 ",list[j]);
}
void main(){
int list[MAX], num;
printf(" Enter the number of elements
");
scanf("%d",&num);
readlist(list,num);
printf("
Elements in the list before sorting are:
");
printlist(list,num);
bub_sort(list,num);
printf("
Elements in the list after sorting are:
");
printlist(list,num);
}
输出
.........................................................