【发布时间】:2016-01-15 16:17:17
【问题描述】:
如果我有一个结构数组,其中包含两个要排序的字段,我该如何实现类似的东西?我已经写了一个修改过的冒泡排序算法来对数组进行排序。
它们应按升序排列,使较小的值在左侧。它们都将是整数值,我只是使用一些字母希望使其更清晰。
假设是一个结构
typedef struct {
int top;
int left;
int right;
int bottom;
}box;
box** boxes = calloc(1, sizeof(box) * 20);
假设所有这些框的每个位置都有从 -100 到 100 的随机值。
我可以按任何一个角对其进行排序。假设我们有这样的顶部和左侧的盒子,我将使用字母作为左侧,但有它以便数组最终排列成这样。
start top, 0,1,2,3,4,5
start left a,b,c,d,e,f
在开始这样的事情之后:
start top, 5,3,1,2,4,0
start left f,d,a,b,e,c
数组的布局如下:
0,1,2,3,4,5,a,b,c,d,e,f
这是我目前使用的排序算法:
static void obj_swap_func(box** a, box** b) {
box* tp = *a;
*a = *b;
*b = tp;
}
void back_2_front(box** a, int count) {
cg_sprite* l, *r;
for (int i = 0; i < count; i++) {
int swap = 0;
for (int j = 0; j < (count - i - 1); j++) {
if (a[j]->l_value > a[j + 1]->l_value) {
obj_swap_func(&a[j], &a[j + 1]);
swap++;
}
}
if (swap == 0) {
break;
}
}
}
我写了这个函数,试图实现下面的答案。
static int greater(box* a, box* b) {
if(a->top < b->top) {
return 0;
}
else if (a->top > b->top) {
return 1;
}
if(a->left < b->left) {
return 0;
}
else if(a->left > b->left) {
return 1;
}
return -1;
}
然后像这样将它添加到循环中: void back_2_front(box** a, int count) { cg_sprite* l, *r;
for (int i = 0; i < count; i++) {
int swap = 0;
for (int j = 0; j < (count - i - 1); j++) {
if(greater(a[j], a[j+1])) {
box_swap_func(&a[j], &a[j + 1]);
swap++;
}
}
if (swap == 0) {
break;
}
}
}
交换函数如下所示:
static void box_swap_func(box** a, box** b) {
box* tp = *a;
*a = *b;
*b = tp;
}
在一组 50 个盒子上运行,结果如下:
box top:-48 box left: 3
box top:-47 box left: 3
box top:-46 box left: 3
box top:-45 box left: 3
box top:-44 box left: 3
box top:-43 box left: 3
box top:-42 box left: 3
box top:-41 box left: 2
box top:-40 box left: 2
box top:-39 box left: 2
box top:-38 box left: 2
box top:-37 box left: 2
box top:-36 box left: 2
box top:-35 box left: 2
box top:-34 box left: 1
box top:-33 box left: 1
box top:-32 box left: 1
box top:-31 box left: 1
box top:-30 box left: 1
box top:-29 box left: 1
box top:-28 box left: 1
box top:-27 box left: 4
box top:-26 box left: 4
box top:-25 box left: 4
box top:-24 box left: 4
box top:-23 box left: 4
box top:-22 box left: 4
box top:-21 box left: 4
box top:-20 box left: 3
box top:-19 box left: 3
box top:-18 box left: 3
box top:-17 box left: 3
box top:-16 box left: 3
box top:-15 box left: 3
box top:-14 box left: 3
box top:-13 box left: 2
box top:-12 box left: 2
box top:-11 box left: 2
box top:-10 box left: 2
box top:-9 box left: 2
box top:-8 box left: 2
box top:-7 box left: 2
box top:-6 box left: 1
box top:-5 box left: 1
box top:-4 box left: 1
box top:-3 box left: 1
box top:-2 box left: 1
box top:-1 box left: 1
box top:0 box left: 1
box top:2 box left: 4
它按顶部排序很好,但您可以看到它们按顶部值正确排序,而不是按左侧值。
我的算法写对了吗?
【问题讨论】:
-
你需要说出 box1 的规则是什么(在代码中)> box2
-
再看一下输出:这些框是按升序排列的,y 坐标比 x 坐标更重要。您在 left 中没有看到顺序是由于缺少共享相同顶部的框。
标签: c arrays algorithm sorting