冒泡在C中排序

我试图在C中实现冒泡排序并且已经到了这么远,但它还没有正确排序。

#include int main() { int n, i, j, a[5], b, temp; printf("Enter the number of elements to be sorted\n"); scanf("%d", &n); for(i = 0; i < n; ++i) { printf("%d - Enter the elements - ", i); scanf("%d", &a[i]); } for(i = 0; i < n; ++i) { for(j = 0; j  a[i+1]) { temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } } } for (i = 0; i < n; ++i) { printf("%d\n", a[i]); } return 0; } 

输入

 2 12 1 13 

产量

 2 1 12 13 

我错过了什么?

所以现在戏剧已经过去了,你的代码的问题在于你没有在你的内循环中使用正确的索引。 另外你的内循环计数器的条件检查不正确。 另外,正如我在你的问题的评论中提到的,你的代码中有一个缺陷(我没有修复),在你向用户询问他们想要输入多少元素之前初始化你的数组。 如果用户输入大于5的数字,这可能导致索引超出范围exception。

 #include int main() { int n, i, j, a[5], b, temp; printf("Enter the number of elements to be sorted\n"); scanf("%d", &n); for(i = 0; i < n; ++i) { printf("%d - Enter the elements - ", i); scanf("%d", &a[i]); } for(i = 0; i < n; i++) { for(j = 0; j < n-1; j++) { if(a[j] > a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } for (i = 0; i < n; ++i) { printf("%d\n", a[i]); } return 0; } 

你的第二个循环不合适。

 for(j=0;j 
 /*By your approach , in inner loop you are not checking the each elements . So change i to j in swapping , and limit of j should be till n-1*/ #include int main() { int n, i, j, a[10], b, temp=0; printf("Enter the number of elements to be sorted\n"); scanf("%d", &n); for(i = 0; i < n; ++i) { printf("%d - Enter the elements - ", i); scanf("%d", &a[i]); } for(i = 0; i < n; ++i) { for(j = 0; j < n-1; ++j) // notice limit , also complexity can be reduced by changing to(j a[j+1]) { temp = a[j]; // changed variable a[j] = a[j+1]; a[j+1] = temp; } } } for (i = 0; i < n; ++i) { printf("%d\n", a[i]); } return 0; } 
  #include int main() { int n, i, j, a[5], b, temp; printf("Enter the number of elements to be sorted\n"); scanf("%d", &n); for(i = 0; i < n; ++i) { printf("%d - Enter the elements - ", i); scanf("%d", &a[i]); } for(i = 0; i < n; ++i) { for(j = 0; j < n; ++j) { if(a[j] > a[j+1]) //change the varible instead of i to j { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } for (i = 0; i < n; ++i) { printf("%d\n", a[i]); } return 0; } 
 /*You May check this code it will help you*/ #include void bubble_sort(int a[],int n); void bubble_sort(int a[],int n) { int i,j; int temp; for(i=0;ia[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } } } main() { int a[10]; int i,n; printf("Enter the number\n"); scanf("%d",&n); printf("Enter the number\n"); for(i=0;i