【发布时间】:2018-10-02 23:29:04
【问题描述】:
我正在编写一个遗传算法,以便解决线性规划的问题,我正在使用 C 语言,当我计算变量的限制时,我将值保存在浮点类型数组中,我需要对该数组进行排序但它删除了我订购时需要的数据:我使用了我编写的 shell_sort 和在标准图书馆员中实现的 qsort,两者都给了我相同的结果,我附加了我使用的算法的代码订购和我用于 qsort () 的比较器功能:
void shell_sort(float *A, int n){
int gap = n/2; //Se obtiene el gap dividiendo el tamaño de arreglo entre dos
int inner, outer, swap; //Variables auxiliares
while (gap > 0) { //Mientras gap sea mayor que zero entonces:
for(outer = gap; outer < n; outer++){ // Para outer igual a gap, siempre que outer sea menor a n, outer aumentara su valor en uno
inner = outer; // inner se iguala al valor de outer
swap = A[inner]; // Swap se iguala a la posiscion inner de A
while (inner > gap - 1 && A[inner - gap] > swap ) { // Mientras inner sea mayor que gap menos 1 y que A en su posicion inner menos gap sea mayor a Swap
A[inner] = A[inner - gap]; //La posicion inner de A tomara como nuevo valor la posicion inner menos gap de A
inner -= gap; //inner decrementa su valor en gap veces
}
A[inner] = swap; //La posicion inner de A tomo como nuevo valor swap
}
gap /=2; // se divide a gap entre dos
}
}
比较函数:
int comp(const void * a, const void * b){
if(*(float*)a < *(float*)b) return -1;
if(*(float*)a == *(float*)b) return 0;
if(*(float*)a > *(float*)b) return 1;
}
输出: Output 我认为当我对数组进行排序时,结果将是 0,26,37,但结果是 26,37,我需要那个零,我真的不知道为什么会这样。
希望有人可以帮助我。
这是我使用排序时的一段代码。
Limites obtenerValoresLimites(lista *l,char var){
//This code works
Limites lim;
restriccion r;
int i,j;
float *aux = (float*)malloc(sizeof(float));
for (i = 0; i < Size(l); i++)
{
r = Element(l,i+1);
for (j = 0; j < strlen(r.variables); j++)
{
if(r.variables[j] == var){
aux[i] = (r.limite/r.coeficientes[j]);
}
}
}
//First print of the output that confirms the zero originally exist
//for (i = 0; i < sizeof(aux)/sizeof(*aux) ;i++)
//printf("%f\n",aux[i]);
//Sorting
//qsort(aux,sizeof(aux)/sizeof(*aux)+1,sizeof(float),comp);
shell_sort(aux,sizeof(aux)/sizeof(*aux));
//printf("\n");
//Second print of the output now the zero is no longer in the array
//for (i = 0; i < sizeof(aux)/sizeof(*aux) ;i++)
//{
// printf("%f\n",aux[i]);
//}
lim.inferior = 0;
lim.superior = aux[(sizeof(aux)/sizeof(*aux))-1];
lim.variable = var;
return lim;
}
感谢您的回答和阅读。
我认为代码有点难以阅读,这是因为我们正在使用一些数据结构来对问题进行建模,所以如果您有兴趣,我们将 gitHub repo 留在下面。
如果您感兴趣,请填写完整代码:https://github.com/JoelRomero97/Metodos-Cuantitativos.git
【问题讨论】:
-
如果你说标准库的 sort 和 qsort 都返回相同的结果,那么我认为问题出在其他地方,也许你认为你的数组中有一个 0,或者你正在传递两个排序功能的大小不正确。向我们展示如何调用排序函数。最好还是发一个minimal reproducible example
-
@Pable,或者他说
qsort也坏了... -
@DavidC.Rankin 是的,我知道,但是
qsort被破坏而不是 OP 的代码被破坏的可能性非常小。qsort并不是昨天由 glibc(或任何其他经过良好测试的 libc 实现)的维护者的朋友编写的。有趣的提示:当我是初学者时,我经常认为我在 libc 中发现了一个错误,因为某些标准功能没有按预期工作,而且总是我错误地使用它。 -
@Pablo 在我的学校里,第一年的学生对我大喊大叫(我是一名助理),因为
read()被“窃听”了;)即使在 4 年后看到他们,我仍然会笑。他们一直在说 6 个小时,然后才终于理解read()的行为;)真正有趣的是一直在说“阅读你错过重要信息的人”。错误是“读取不按我的要求读取 n 字节,但更少”他们正在读取标准输入......
标签: c arrays quicksort genetic-algorithm shellsort