快速排序用C未按预期 [英] QuickSort in C not working as expected

查看:129
本文介绍了快速排序用C未按预期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用C来实现快速排序,但没有得到正确的结果。这是我写的程序。

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");
}

我给输入为0,4,2,7但结果是4,0,7,2。我能不能找到这个code中的问题。有人可以帮我吗?

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 ?

推荐答案

您的for循环应该是:为(J =低; J&LT;高; J ++)

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

看一看Coreman的算法导论,我觉得这是直掉在那里。

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

请参见 http://ideone.com/Ug​​ouy4

这篇关于快速排序用C未按预期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆