2025年02月25日 解释C语言中的排序技术 极客笔记
C语言中有哪些不同的排序技术?请用例子解释其中一种排序技术。
C语言提供了五种排序技术,如下所示:
这是最简单的排序技术,也被称为交换排序。
对列表中的其他元素重复相同的步骤,直到所有元素都排序完成。
30 50 40 10 20
考虑以下给出的元素−
将第一个元素与剩余元素比较。
10 50 40 30 20
将第二个元素与剩余的元素进行比较。
10 20 50 40 30
将第三个元素与剩下的元素进行比较。
10 20 30 50 40
将第四个元素与剩余元素进行比较。
10 20 30 40 50
按照以下所述,参考冒泡排序的步骤。
for (i=0; i<n-1; i++){
for (j=i+1; j<n; j++){
if (a[i] > a[j]){
t=a[i];
a[i] = a[j];
a[j] = t;
}
}
}
以下是用C语言实现的冒泡排序技术的程序-
#include<stdio.h>
int main(){
int a[50], i,j,n,t;
printf("enter the No: of elements in the list:
");
scanf("%d", &n);
printf("enter the elements:
");
for(i=0; i<n; i++){
scanf ("%d", &a[i]);
}
printf("Before bubble sorting the elements are:
");
for(i=0; i<n; i++)
printf("%d \t
", a[i]);
for (i=0; i<n-1; i++){
for (j=i+1; j<n; j++){
if (a[i] > a[j]){
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
printf ("after bubble sorting the elements are:
");
for (i=0; i<n; i++)
printf("%d\t", a[i]);
return 0;
}
当上述程序被执行时,会产生以下结果-
enter the No: of elements in the list:
5
enter the elements:
12 11 45 26 67
Before bubble sorting the elements are:
12
11
45
26
67
after bubble sorting the elements are:
11 12 26 45 67
本文链接:http://so.lmcjl.com/news/23867/