c - 冒泡排序疑惑

标签 c sorting

#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/

相关文章:

当我在 linux 中执行此代码时,c 指针以相反的方式递增

java - 为什么合并排序用于 Android/Java API 中的对象?

vfork后可以调用dup2吗?

c++ - C++ 17 POSIX信号量或condition_variable?

html - Live Audio Streaming 到浏览器的方法,一定很简单

对 map[string][]struct{} 进行排序

python - Pandas:如何对多级 DataFrame 中子级的最大 3 个值求和

python - python中嵌套字典的排序列表

javascript - 按两个值对其中包含 JS 对象的数组进行排序

c - 从输入中获取数字的最佳方式?