#include<stdio.h>
#include<conio.h>
int main( )
{
int a[100];
int i, j, temp, n ;
printf("how many numbers you want to sort : \n");
scanf("%d",&n);
printf("Enter %d number values you want to sort\n", n);
for(j=0; j<n; j++)
scanf("%d",&a[j]);
for(j=1;j<n;j++)
我们怎么知道上面提到的for循环必须重复n次,应该如何开发逻辑,我知道内部for循环只能帮助对列表中的元素进行一次排序,那我们为什么要这样做重复内循环n次
{
for(i=0; i<n; i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
printf ( "\n\nArray after sorting:\n") ;
for ( i = 0 ; i <n ; i++ )
printf ( "%d\t", a[i] ) ;
getch();
}
最佳答案
在内部循环中你会找到最大值。您无法确定其他数字是否已排序。
其他版本(更快):
do
for (i = 0; i < n-1; i++) do:
if A[i] > A[i+1] then
swap(A[i], A[i+1])
end if
end for
n = n-1
当 n > 1
(不检查先前循环的最大值)
关于c - 冒泡排序疑惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30116321/