仅使用 while 和 if 对数组进行排序

Sorting array only with while and if

我在尝试 运行 程序时收到一条消息。为什么?

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 语句中。 你怎么看?为什么会这样?我认为我以积极的方式使用指向数组的指针。

谢谢!

在你的内部循环中,你递增 i 超出数组的大小。您的算法应该要求您递减 i,但我不确定这是否足以修复排序算法。

您应该首先尝试使用单个 while 循环来实现 冒泡排序,在该循环中比较相邻的项目并在交换它们时后退。

你程序中的这个循环

    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;
        }
    }
}