上代码先:
void printlistvalue(int list[], int len)
{
for (int i = 0;i < len;i++) {
if( i != len - 1 )
printf(" %d,",list[i]);
else {
printf(" %d\n",list[i]);
}
}
}
int core_sort(int list[], int left, int right, int len)
{
if (nullptr == list)
return -1;
//selet a key value from list
int key, low, high;
low = left;
high = right;
key = list[left];//select left value as the key
printlistvalue(list, len);
while ( low < high ) {
while ( low < high && list[low] < key )
{
low++;
}
while (low < high && list[high] > key) {
high--;
}
printf(" exchange postion is %d,%d; key = %d\n", low, high, key);
int temp = list[low];
list[low] = list[high];
list[high] = temp;
printlistvalue(list, len);
}
printf(" core_sort exit while. return pos:%d\n",low);
printlistvalue(list, len);
list[low] = key;
return low;
}
void quick_sort(int list[], int start, int end, int len)//start from 0, end is list len - 1
{
if ( nullptr == list || start >= end )
{
printf("The start or end value is invalid!\n");
return;
}
printf("quick_sort start===>\n");
int retIdx = core_sort(list, start, end, len);
if (retIdx < 0 )
return;
if ( start < retIdx - 1 )
{
quick_sort(list, start, retIdx -1, len);
}
if ( retIdx + 1 < end )
{
quick_sort(list, retIdx + 1, end, len);
}
}
注:原本快速排序的partion函数,这里名称修改为core_sort, 而且多加了一个参数"len",便于传递给打印函数printlistvalue.
经过调试发现, core_sort有待改进的地方:
- 在 while ( low < high )循环中,最后交换low和high的值,在交换之前应该有个low和high是否相等的判断,不然要做无用功了。
- 通常给出的代码,退出循环后,要把key值赋给当前low,多余了。
- 目前代码只适用于list 中没有重复的数值,比如给一个list = {1,1,1,12,1,1,1}; ,会死循环!
改进方案【第三点还没解决】:
void printlistvalue(int list[], int len)
{
for (int i = 0;i < len;i++) {
if( i != len - 1 )
printf(" %d,",list[i]);
else {
printf(" %d\n",list[i]);
}
}
}
int core_sort(int list[], int left, int right, int len)
{
if (nullptr == list)
return -1;
//selet a key value from list
int key, low, high;
low = left;
high = right;
key = list[left];//select left value as the key
printlistvalue(list, len);
while ( low < high ) {
while ( low < high && list[low] < key )
{
low++;
}
while (low < high && list[high] > key) {
high--;
}
if (low != high)
{
printf(" exchange postion is %d,%d; key = %d\n", low, high, key);
int temp = list[low];
list[low] = list[high];
list[high] = temp;
printlistvalue(list, len);
}
}
printf(" core_sort exit while. return pos:%d\n",low);
printlistvalue(list, len);
return low;
}
void quick_sort(int list[], int start, int end, int len)//start from 0, end is list len - 1
{
if ( nullptr == list || start >= end )
{
printf("The start or end value is invalid!\n");
return;
}
printf("quick_sort start===>\n");
int retIdx = core_sort(list, start, end, len);
if (retIdx < 0 )
return;
if ( start < retIdx - 1 )
{
quick_sort(list, start, retIdx -1, len);
}
if ( retIdx + 1 < end )
{
quick_sort(list, retIdx + 1, end, len);
}
}