排序是任何编程语言中我们都需要学习的必要概念。大多数排序是在涉及数字的数组上完成的,是掌握遍历和访问数组中数据的技术的垫脚石。
我们在今天的文章中要讨论的排序技术类型是冒泡排序。
冒泡排序是一种简单的排序算法,如果相邻元素的顺序错误,它的工作原理是重复交换相邻元素。这种数组排序方法不适合大型数据集,因为平均和最坏情况情况下的时间复杂度非常高。
下面是冒泡排序的实现。如果内部循环没有引起任何交换,可以通过停止算法来优化它。
// Easy implementation of Bubble sort
#include <stdio.h>
int main(){
int i, j, size, temp, count=0, a[100];
//Asking the user for size of array
printf("Enter the size of array you want to enter = \t");
scanf("%d", &size);
//taking the input array through loop
for (i=0;i<size;i++){
printf("Enter the %dth element",i);
scanf("%d",&a[i]);
}
//printing the unsorted list
printf("The list you entered is : \n");
for (i=0;i<size;i++){
printf("%d,\t",a[i]);
}
//sorting the list
for (i = 0; i < size - 1; i++) {
count = 1;
for (j = 0; j < size - i - 1; j++) {
if (a[j] > a[j + 1]) {
//swapping elements
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
count = 1;
}
}
// If no two elements were swapped by inner loop,
// then break
if (count == 1)
break;
}
// printing the sorted list
printf("\nThe sorted list is : \n");
for (i=0;i<size;i++){
printf("%d,\t",a[i]);
}
return 0;
}
**
时间复杂度:o(n2)
辅助空间:o(1)
有任何疑问请评论!!
所有讨论都将受到赞赏:)
以上就是C 中的冒泡排序的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号