c - 在 C 中对二维结构数组进行排序时出现问题

标签 c

我有一个 (150x150)2d 结构数组,我想以独立于行的方式对其进行排序。因为它是一个结构,我不相信(如果我错了,请纠正我)我不能使用 qsort() 或者至少不知道如何使用,因为我正在解析结构并且我正在比较的元素是一个违反 qsort() 比较原型(prototype)要求的 double 值。无论如何,我想在

上应用快速排序
  struct my_struct {
    int x;
    int y;
    double d;
 };
void quicksort(struct my_struct* array,int start, int end)
{

struct my_struct key, Pivot;
int i,j,PivotPoint;
if(start< end)
{
    PivotPoint = (start+end)/2;
    theswap(&array[start], &array[PivotPoint]);
    key = array[start];
    i= start+1;
    j = end;
    while (i<=j)
    {
        while((i<=end) && (array[i].d <= key.d))
            ++i;
        while ((j>=start) && array[j].d> key.d) {
            --j;
            if (i<j) {
                theswap(&array[i], &array[j]);
            }
        }
    }
    theswap(&array[start], &array[j]);
    quicksort(array, start, j-1);
    quicksort(array, j+1, end);
    }
}
void theswap(struct my_struct *a, struct TourElement *b)
{
struct my_struct t;
t=*a; 
*a=*b;
*b=t;
}

在我的主要功能中 我有一些东西 像这样:

 for (i=0;i<150;++i)
   {
   for (j=0;j<150;++j)
   { 
    My_array[i][j].x = somethingUseful;
    My_Array[i][j].y = somethingEquallyUseful;
    My_Array[i][j].d = CalcD(somethingUseful,somethingEquallyUseful);
    }
    qsort(My_Array[i],150,sizeof(my_struct),compare);
   }


       int compare(struct my_struct a , struct my_struct b)
     {
          return a.d -b.d;
     }

当我执行快速排序时,应用程序挂起,经过进一步调查,快速排序函数中的数组中似乎没有任何元素。 (我在快速排序的开头添加了一个 for 循环 printf 来逐项列出结构体的 d 值,但没有打印任何内容)

任何人都可以确定我在这里做错了什么吗?我没有收到任何编译错误。并且“D”计算正确。

最佳答案

你可以使用std c qsort

void qsort( void *buf, size_t num, size_t size, int (*compare)(const void *, const void *) );

比较函数是这样的:

int my_struct_comp(const void *p1, const void *p2){
  my_struct *mp1 = (my_Struct*)p1;
  my_struct *mp2 = (my_Struct*)p2;

  返回 mp1->d - mp2->d;
}

你可以调用 qsort (其中 len 是数组的长度)

qsort(myarray, len, sizeof(my_struct), &my_struct_cmp);

关于c - 在 C 中对二维结构数组进行排序时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9959170/

相关文章:

我可以在 linux 中获得与 mesa 的 opengl 兼容性上下文吗?

c - C问题中的嵌套结构

c - 在Linux内核模块中使用线程的问题

c - 如何将 int 数组(保存十六进制浮点值)转换回 C 中的浮点值

c - 在C中随机化一个字符串

c - free() 无效指针

c - 为什么不推荐使用 fgets 函数?

如果大小为 0,是否可以使用空指针调用 memset()?

c++ - 如何在 FFmpeg C/C++ 中寻找

C++字符串问题