Luke Collins
Luke Collins

Reputation: 1463

Why is my random array & sort program not working?

I've tried looking up similar questions but I haven't seemed to find anything which solves my problem.

I need to write a program which generates an array of random numbers and sorts them via insertion sort. The actual randomness of the array isn't that important; the important thing is that the code itself generates them. I read here that rand() % n+1 is sufficient for my needs to generate a number between 1 and n.

The code for my program is:

/*
 * Task 1, question e
 */
#include <stdio.h>
#include <stdlib.h>

//Random Array Length
#define L 10
#define MAX 100

void naive_sort(int[]);

int main(){

    int i, a[L];

    //Generate an array of random numbers
    for(i=0; i<L; i++)
        a[i]= rand() % (MAX+1);

    //Unsorted Array
    printf("\nUnsorted array: ");
    for(i=0; i<L; i++)
            printf("%d    ", a[i]);

    //Sorted Array
    naive_sort(a);

    return 0;
}

void naive_sort(int a[]){
    int i, j, t;

    for(i=1; i < L; i++){
        t=a[i];
        j=i-1;
        while((t < a[j]) && (j >= 0)){
            a[j+1] = a[j];
            j--;
        }
        a[j+1]=t;
    }

    printf("\nSorted array: ");
    for(i=0; i<L; i++)
        printf("%d    ", a[i]);
}

The algorithm just seems to be repeating some numbers and not sorting the list at all.

Output

Any help with the issue would be greatly appreciated, I've even tried duck debugging but that doesn't seem to work either!

Upvotes: 0

Views: 179

Answers (2)

Georg Fuss
Georg Fuss

Reputation: 315

On my PC [kubuntu, g++] your code works.

Putting some print-statements in your program can help you. The sorting routing-function you should call insert-sort.

Georg Fuss

Upvotes: 2

Gffgh
Gffgh

Reputation: 23

You are assigning to a[L] instead of a[i].

In the sorting loop you're assigning the same t to several a[j+1], that can't be right. The original uses a[j] instead.

Switch the order of the two conditions of thebwhile loop. Current order invokes undefined behaviour by reading a[-1] before checking that j is still >= 0.

Upvotes: 2

Related Questions