Search code examples
cqsort

qsort in C give wrong results


I am trying to sort an array of structs (A SJF Scheduler). I am using the qsort library function to sort the structs in increasing order according to the attribute bursttime. However, the output is not correct. I've checked some SO questions about the same but they served no use.

struct job
{
    int jobno;
    int bursttime;
};
typedef struct job job_t;

int mycompare(const void* first, const void* second)
{
    int fb = ((job_t*)first)->bursttime;
    int sb = ((job_t*)second)->bursttime;
    return (fb - sb);
}

int main()
{
    int n;
    printf("Enter number of jobs: ");
    scanf("%d", &n);
    job_t* arr = (job_t*)malloc(sizeof(job_t) * n);
    for(int i = 1; i <= n; ++i)
    {
        printf("Enter Burst time for Job#%d: ",i);  
        scanf("%d", &(arr[i].bursttime));
        arr[i].jobno = i;
    }

    printf("\n");
    printf("Order of the Jobs before sort:\n");
    for(int i = 1; i <= n; ++i)
    {
        printf("%d\t", arr[i].jobno);
    }

    qsort(arr, n, sizeof(job_t), mycompare);    

    printf("\n");
    printf("Order of the Jobs after sort:\n");
    for(int i = 1; i <= n; ++i)
    {
        printf("%d\t", arr[i].jobno);
    }
    printf("\n");
    printf("\n");
    return 0;
}

This is my inputfile:

4
7
2
9
4

The output I'm getting is:

Order of the Jobs before sort:
1   2   3   4   
Order of the Jobs after sort:
2   1   3   4   

The expected order should be: 2,4,1,3. Am I missing anything?


Solution

  • At least this problem

    for(int i = 1; i <= n; ++i) // bad
    

    Use zero base indexing.

    for(int i = 0; i < n; ++i)