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[L]= 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] = t;
j--;
}
a[j+1]=t;
}
printf("\nSorted array: ");
for(i=0; i<L; i++)
printf("%d ", a[i]);
}
I notice that the array generated has numbers larger than 100, despite defining MAX
to be 100. The sorting also doesn't work. This is what I get as an output:
Any help with the issue would be greatly appreciated, I've even tried duck debugging but that doesn't seem to work either!
Aucun commentaire:
Enregistrer un commentaire