It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center
                            
                        
                    
                
                                7年前关闭。
            
                    
我正在尝试在C中实现冒泡排序算法。这是到目前为止的内容:

#include<stdio.h>
void bubble_sort(int m, int a[100000]);
void main()
{
int a[100000], i, m;
FILE * be;

be=fopen("be.txt","r");
for (i=0; !(feof(be)); ++i)
    fscanf(be,"%i", a+i);
m=i-1;
bubble_sort(m ,a);
fclose(be);
}
void bubble_sort(int m, int a[100000])
{
int i, ok, v, n=m;;
for (;!ok;ok=1)
{
    ok=0;
    for (i=0;i<=m-1;++i)
    {
        if (*(a+i)>*(a+i+1)) { v=*(a+i); *(a+i)=*(a+i+1); *(a+i+1)=v; ok=0;}
    }
    m=m-1;
}

for (i=0; i<n; ++i)
    printf("%i ", a[i]);
}


我的伪代码:

Bubblesort2( A )
m:=length( A ) - 1
repeat
    OK := true
    for i := 0 to m-1 do
        if Ai > Ai+1 then
            Ai <=>Ai+1
            OK := false
    m := m - 1
until OK


这行不通。在C中实现气泡排序的代码是什么?

最佳答案

尝试这个:

void bubble_sort(int m, int a[100000])
{
    int i, ok = 0, v, n = m;
    while ( !ok )
    {
        ok = 1;
        for ( i=0; i < m-1; ++i )
        {
            if ( *(a+i) > *(a+i+1) )
            {
                v = *(a+i);
                *(a+i) = *(a+i+1);
                *(a+i+1) = v;
                ok = 0;
            }
        }

        m--;
    }

    for ( i = 0; i < n; ++i )
        printf("%i ", a[i]);
}


基本上,初始化确定(使用垃圾值初始化局部变量)。进入循环时,还必须设置ok = 1,如果发生交换,则必须设置ok = 0。使用for循环没有意义,while循环更具可读性。 m = m - 1可以替换为m--,这是同一件事,并且您编写的代码更少。

10-06 13:31