QuickSort in C not working as expected

时间秒杀一切 提交于 2019-12-12 06:19:53

问题


I tried to implement QuickSort in C, but not getting the correct result. This is the program i wrote.

#include<stdio.h>
int partition(int a[],int low,int high)
{
    int pivot = a[high];
    int temp;
    int i = low-1;
    int j=0;
    for(j=0;j<high-1;j++)
    {
        if(a[j]<=pivot)
        {
            i=i+1;
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;    
        }       
    }
    temp = a[i+1];
    a[i+1] = pivot;
    a[high] = temp;
    return (i+1);   
}

void quick_sort(int a[],int low,int high)
{
    if(low<high)
    {
        int q = partition(a,low,high);
        quick_sort(a,low,q-1);
        quick_sort(a,q+1,high);
    }
}

main()
{
    int i,n,a[10];
    printf("\nEnter the number of elements in the array : ");
    scanf("%d",&n);
    printf("\nEnter the elements in the array : "); 
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("\nElements in the array before sorting : ");    
    for(i=0;i<n;i++)
    {
        printf (" %d",a[i]);
    }
    quick_sort(a,0,n-1);
    printf("\nElements in the array after sorting : "); 
    for(i=0;i<n;i++)
    {
        printf (" %d",a[i]);
    }
    printf("\n");
}

I gave input as 0,4,2,7 but the result is 4,0,7,2. I couldn't able to find the issue with this code. Can someone help me ?


回答1:


Your for loop should be: for(j=low;j<high;j++)

Have a look at Coreman's Introduction to algorithms, I think this is straight out of there.

see http://ideone.com/Ugouy4



来源:https://stackoverflow.com/questions/30686270/quicksort-in-c-not-working-as-expected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!