c - 快速排序程序不起作用?

标签 c algorithm gridview-sorting

这应该是快速排序算法的实现。但是当我运行它时,它会永远运行而不显示任何内容。我试图找到问题所在,但现在太累了。请帮忙。

#include <stdio.h>

void quicksort(int arr[], int pivotIndex,int right);
int partition(int a[],int left,int right);

int main()
{
   int arr[5] = {5, 4,2, 3, 6};    
   int left = 0;
   int right = 4;

   quicksort(arr, left, right);

   for (int i = 0; i < 5; i++)
   {
       printf("%d ", arr[i]);
   }
   return 0;    
}

void quicksort(int arr[], int left,int right)
{
    if (left < right)
    {
        int pivotNewIndex = partition(arr, left, right);
        quicksort(arr, left, pivotNewIndex - 1);
        quicksort(arr, pivotNewIndex + 1, right);
    }
}

int partition(int a[],int left,int right)
{

    int i = left;
    int j = right;
    int pivotIndex = left;
    int temp;

    while (i < j)
    {
        while (a[pivotIndex] <=a[j])
        {
            j--;
        }
        if (a[pivotIndex] > a[j])
        {
            temp = a[pivotIndex];
            a[pivotIndex] = a[j];
            a[j] = temp;
            pivotIndex = j;
        }

        while (a[pivotIndex] <= a[j])
        {
            i++;
        }
        if (a[pivotIndex] < a[j])
        {
            temp = a[pivotIndex];
            a[pivotIndex] = a[j];
            a[j] = temp;
            pivotIndex = i;
        }        
    }
    return pivotIndex;
}

最佳答案

测试

if (left < right)

将始终为真,因为您从不修改变量(您将它们按值传递给其他函数,因此您正在修改副本)。

您正在使用永远不会改变的左/右值递归地进行此测试。

PS:我不知道这是否是您的程序/算法的唯一问题

关于c - 快速排序程序不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23725889/

相关文章:

c# - 如何对忽略空白行的datagridview进行排序

c# - 使 DataGridViewColumn 可排序

c - 字符串的一部分转换为 int (C)

c++ - 维基百科上的线性插值代码——我不明白

algorithm - 关于算法分析的一些问题

javascript - 根据路径距离的分数从具有多个点的路径获取坐标

C 中结构的副本

c++ - 如何在eclipse中获取空格而不是制表符

c++ - 实现哈希表