代码之家  ›  专栏  ›  技术社区  ›  W.N

仅使用while和if对数组排序

  •  0
  • W.N  · 技术社区  · 9 年前

    Segmentation fault
    

    我的代码:

    #include <stdio.h>
    
    void sort_array(int *arr, int s);
    
    int main() {
        int arrx[] = { 6, 3, 6, 8, 4, 2, 5, 7 };
    
        sort_array(arrx, 8);
        for (int r = 0; r < 8; r++) {
            printf("index[%d] = %d\n", r, arrx[r]);
        }
        return(0);
    }
    
    sort_array(int *arr, int s) {
        int i, x, temp_x, temp;
        x = 0;
        i = s-1;
        while (x < s) {
            temp_x = x;
            while (i >= 0) {
                if (arr[x] > arr[i]) {
                    temp = arr[x];
                    arr[x] = arr[i];
                    arr[i] = temp;
                    x++;
                }
                i++;
            }
            x = temp_x + 1;
            i = x;
        }
    }
    

    我认为问题在于 if 陈述 你怎么认为?为什么会这样?我想我用积极的方式使用指向数组的指针。

    非常感谢。

    2 回复  |  直到 9 年前
        1
  •  2
  •   Vlad from Moscow    9 年前

    程序中的此循环

        while (i >= 0) {
            //...
            i++;
        }
    

    没有意义,因为 i 无条件地增加。

    程序可以如下所示

    #include <stdio.h>
    
    void bubble_sort( int a[], size_t n )
    {
        while ( !( n < 2 ) )
        {
            size_t i = 0, last = 1;
    
            while ( ++i < n )
            {
                if ( a[i] < a[i-1] )
                {
                    int tmp = a[i]; 
                    a[i] = a[i-1];
                    a[i-1] = tmp;
                    last = i;
                }
            }
    
            n = last;
        }
    }   
    
    int main( void ) 
    {
        int a[] = { 6, 3, 6, 8, 4, 2, 5, 7 };
        const size_t N = sizeof( a ) / sizeof( *a );
    
        for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
        printf( "\n" );
    
        bubble_sort( a, N );
    
        for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
        printf( "\n" );
    
        return 0;
    }
    

    程序输出为

    6 3 6 8 4 2 5 7 
    2 3 4 5 6 6 7 8 
    

    如果希望排序函数只有一个while循环,那么可以按以下方式实现

    void bubble_sort( int a[], size_t n )
    {
        size_t i = 0;
    
        while ( ++i < n )
        {
            if ( a[i] < a[i-1] )
            {
                int tmp = a[i]; 
                a[i] = a[i-1];
                a[i-1] = tmp;
                i = 0;
            }
        }
    }
    
        2
  •  2
  •   chqrlie    9 年前

    在内部循环中,您会增加 i 但我不确定这是否足以修复排序算法。

    气泡排序 有一个单人间 while 在循环中比较相邻项目,并在交换时后退一步。