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

标签 c arrays sorting while-loop bubble-sort

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

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

谢谢!

最佳答案

你程序中的这个循环

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

关于c - 仅使用 while 和 if 对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38401088/

相关文章:

c - C 中使用 printf 打印宏变量

Android 按下了数组中的哪个按钮索引

php - 保存每个 ACF 重复器字段行的值并将所有值放入一个数组 (PHP)

c++ - libjpeg:复制整个数据

c - 带控件的 DialogEx : Resizing?

python - 优化音频 DSP 程序的 numpy 计算

C中不区分大小写的排序

sorting - Elasticsearch 按字母顺序排序,然后按数字排序

javascript - 如何使用 jquery 对具有本地字符的项目进行排序?

c - 如何获取二元组最后一个元素以外的元素?