简单的冒泡排序程序.它可以完美地工作约85%的时间,但在某些情况下无法对列表进行排序 [英] Simple Bubble sort program. It works flawlessly about 85% of times but in some cases it doesn't sort the list
本文介绍了简单的冒泡排序程序.它可以完美地工作约85%的时间,但在某些情况下无法对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
main() {
int ctr, inner, outer, didSwap, temp;
int nums[10];
time_t t;
srand(time(&t));
for (ctr = 0; ctr < 10; ctr++) {
nums[ctr] = (rand() % 99) + 1;
}
printf("\nHere is the list before the sort:\n");
for (ctr = 0; ctr < 10; ctr++) {
printf("%3d", nums[ctr]);
}
// Sorting the array
for (outer = 0; outer < 9; outer++) {
didSwap = 0;
for (inner = outer + 1; inner < 10; inner++) {
if (nums[inner] < nums[outer]) {
temp = nums[inner];
nums[inner] = nums[outer];
nums[outer] = temp;
didSwap = 1;
}
}
if (didSwap == 0) {
break;
}
}
printf("\n\nHere is the list after sorting:\n");
for (ctr = 0; ctr < 10; ctr++) {
printf("%3d", nums[ctr]);
}
printf("\n");
return 0;
}
有时它不能正确地对列表进行排序,有时甚至根本无法排序.错误屏幕截图
Sometimes it doesn't sort the list properly and sometimes doesn't sort at all. Screenshot of error
推荐答案
您没有在使用冒泡排序.这是一个选择排序算法,您的代码不正确.我已经更新了气泡排序算法的代码.
You are not using bubble sort. this is a selection sort algorithm and your code is not correct. I have updated the code for the bubble sort algorithm.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int ctr, inner, outer, didSwap, temp;
int nums[10];
time_t t;
srand(time(&t));
for (ctr = 0; ctr < 10; ctr++) {
nums[ctr] = (rand() % 99) + 1;
}
printf("\nHere is the list before the sort:\n");
for (ctr = 0; ctr < 10; ctr++) {
printf("%3d", nums[ctr]);
}
// bubble Sorting the array
for (outer = 0; outer < 9; outer++) {
didSwap = 0;
for (inner = 0; inner < 9-outer; inner++) {
//repeatedly swapping the adjacent elements if they are in wrong order
if (nums[inner] > nums[inner+1]) {
temp = nums[inner];
nums[inner] = nums[inner+1];
nums[inner+1] = temp;
didSwap = 1;
}
}
if (didSwap == 0) {
break;
}
}
printf("\n\nHere is the list after sorting:\n");
for (ctr = 0; ctr < 10; ctr++) {
printf("%3d", nums[ctr]);
}
printf("\n");
return 0;
}
这篇关于简单的冒泡排序程序.它可以完美地工作约85%的时间,但在某些情况下无法对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文