#include <stdio.h>
#define ARRAY_SIZE 10
void lomuto (int A[], int l, int r, int smallerAtLeft)
{
if (smallerAtLeft == 1) //move elements smaller than pivot to the left and the greater ones to the right
{
int tmp, tmp2,pivot,i,j;
pivot = A[r];
i = l-1;
for (j =0; j<r-1; j++)
{
if (A[j] <= pivot)
{
i++;
tmp = A[i];
A[i] = A[j];
A[j] = tmp;
}
}
tmp2 = A[i+1];
A[i+1] = A[r];
A[r] = tmp2;
}
if (smallerAtLeft == 0) //move elements smaller than pivot to the right and the greater ones to the left
{
int tmp3, tmp4,pivot,i,j;
pivot = A[r];
i = l-1;
for (j=0; j<r-1; j++)
{
if (A[j]>= pivot)
{
i++;
tmp3 = A[i];
A[i] = A[j];
A[j] = tmp3;
}
}
tmp4 = A[i+1];
A[i+1] = A[r];
A[r] = tmp4;
}
}
void quicksort (int A[], int l, int r, int ascending)
{
lomuto (A,l,r,ascending);
}
int main()
{
int testarray;
int testArray[ARRAY_SIZE] = {4, 2, 5, 3, 6, 7, 8, 1, 0};
quicksort (testarray,0,8,1);
return testarray;
}
晚上好。通常,我几乎在每个论坛和最深的线程中搜索我的代码中的可疑性。但是这次我没有找到可以帮助我的答案。如果有人能告诉我为什么 code-exe 停止工作,但在编译过程中屏幕上没有显示错误,我将不胜感激。我们必须使用 lomuto 分区实现快速排序算法。如果变量 "smallAtLeft" 等于 1,则数组应按递增属性排序,如果等于 0,则递减。
此外,我们必须实现 void 函数,就像您在代码中看到的那样。包含 lomuto 的"lomuto-fct"和"quicksort-fct"。
也许这个反向Lomuto线程将来也会帮助其他人。
您不了解main
的返回值是什么以及它的用途。它通常是成功和失败的指标,典型值0
成功,小的正值表示失败。在<stdlib.h>
头文件中甚至还有为此目的定义的宏:EXIT_SUCCESS
和EXIT_FAILURE
。
如果你想看到排序的数组,你需要打印它:
printf("Sorted array = {");
for (unsigned i = 0; i < ARRAY_SIZE; ++i)
{
printf(" %d", testArray[i]);
}
printf(" }n");
这当然需要您将实际数组传递给排序函数。