快速排序问题(一直死循环)
本帖最后由 qwe1231069 于 2017-2-26 15:18 编辑#include <stdio.h>
void quick_sort(int carry[], int left, int right);
void quick_sort(int carry[], int left, int right)
{
int i, j, middle, temp;
middle = carry[(left + right) /2];
i = left;
j = right;
while(i <= j)
{
while(carry < middle)
{
i++;
}
while(carry > middle)
{
j--;
}
if(i <j)
{
temp = carry;
carry = carry;
carry = temp;
i++;
j--;
}
}
if(left < j)
{
quick_sort(carry, left, j);
}
if (i < right)
{
quick_sort(carry, i, right);
}
}
int main()
{
int carry [] = {1, 2, 34, 46, 356, 11, 567, 65, 234, 64, 123, 64, 22,78};
int i;
int length = (sizeof(carry) / sizeof(carry));
quick_sort(carry, 0, length - 1);
for(i = 0; i < length; i++)
{
printf("%d ", carry);
}
putchar('\n');
return 0;
}
我就是按照小甲鱼教的做的,结果一直死循环。
我调试的结果是i和j最终指向同一个值,然后死循环。
想不明白,求解! #include <stdio.h>
void quick_sort(int carry[], int left, int right);
void quick_sort(int carry[], int left, int right)
{
int i, j, middle, temp;
middle = carry[(left + right) / 2];
i = left;
j = right;
while(i <= j)
{
while(carry < middle)
{
i++;
}
while(carry > middle)
{
j--;
}
//if(i <j)
if(i <=j)
{
temp = carry;
carry = carry;
carry = temp;
i++;
j--;
}
}
if(left < j)
{
quick_sort(carry, left, j);
}
if(i < right)
{
quick_sort(carry, i, right);
}
}
int main()
{
int carry[] = {1, 2, 34, 46, 356, 11, 567, 65, 234, 64, 123, 64, 22,78};
int i;
int length = (sizeof(carry) / sizeof(carry));
quick_sort(carry, 0, length - 1);
for(i = 0; i < length; i++)
{
printf("%d ", carry);
}
putchar('\n');
return 0;
}
页:
[1]