简体   繁体   English

C中的冒泡排序:函数未更改数组数据

[英]Bubble sort in C: Function not changing array data

Code: 码:

#include <stdio.h>

void testSort(int values[], int n);

int main(void)
{
    int hs[] = {5,3,2,1,4};
    printf("Unsorted: %i %i %i %i %i\n", hs[0], hs[1], hs[2], hs[3], hs[4]);
    testSort(hs, 5);

    printf("Sorted: %i %i %i %i %i\n", hs[0], hs[1], hs[2], hs[3], hs[4]);
}

void testSort(int values[], int n)
{
    for (int i = 0; i < n-1; i++)
    {
        int hold;
        int current = values[i];
        int next = values[i + 1];

        if (current > next)
        { 
            hold = current;
            current = next;
            next = hold;
        }
    }
    return;
}

I'm trying to do bubble sort and right now it goes through the array once, but my question is: Why isn't my hs[] updating after calling function? 我正在尝试进行冒泡排序,现在它一次通过数组,但是我的问题是:为什么在调用函数后我的hs[]更新? The second printf shows that it remained the same. 第二个printf显示它保持不变。

EDIT: As mentioned, turns out I was changing data but of the copies . 编辑:如前所述,原来我是在更改数据,但在副本中 For some reason I when I created the variables current/next I felt as if they were representing values[i]/values[i+1] but in reality I was just creating new variable and passing the value of values[0] which is 5 and assigning it to current . 出于某种原因,我在我创建的变量current/next我感觉好像他们是表示 values[i]/values[i+1]但在现实中我刚创建新的变量和传递的 values[0]其是5并将其分配给current Obviously leaving values[] unchanged. 显然,values []保持不变。 Thanks everyone 感谢大家

The problem is that you're only modifying the function's local variables, not the array's elements. 问题在于您仅在修改函数的局部变量,而不是数组的元素。

It's the same principle as why this program will print 1 and not 2 : 这与为什么该程序将输出1而不是2原理相同:

int main()
{
    int array[] = {1};
    int x = array[0];
    x = 2;
    printf("array[0] = %d\n", array[0]);
    return 0;
}

You need to assign values to the array's elements: 您需要为数组的元素分配值:

void testSort(int values[], int n)
{
    for (int i = 0; i < n-1; i++)
    {
        if (values[i] > values[i+1])
        { 
            int hold = values[i];
            values[i] = values[i+1];
            values[i+1] = hold;
        }
    }
}

Once you've fixed this, you will notice that this function only works for some inputs. 修复此问题后,您会注意到该功能仅适用于某些输入。
Solving that bug is left as an exercise. 解决该错误作为练习。

Please try below code:- 请尝试以下代码:-

 void bubble_sort(int list[], int n){
      int c, d, t;
      for (c = 0 ; c < ( n - 1 ); c++)
      {
         for (d = 0 ; d < n - c - 1; d++)
          {
             if (list[d] > list[d+1])
             {
                 t         = list[d];
                 list[d]   = list[d+1];
                 list[d+1] = t;
             }
          }
     }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM