Hey, I am trying to generate random strings and sort'em using heap sort. It sorts well but there is a problem. The sorted array doesn't include the first generated string. Instead of it, it gives me a random string. I tested the random functions, I think they are ok.
So, here is the full code, I hope somebody can help me.
PHP Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
char* random_fill(int n, const char *src)
{
char *s;
s = (char*) malloc (n*sizeof(char));
int src_len = strlen(src);
int i;
for (i = 0; i < n; i++)
{
s[i] = src[rand() % src_len];
}
return s;
}
int randomNum(int max){
int n;
n = rand()%max+1;
return n;
}
void percDown(char** array,int root,int bottom);
void heapSort(char** array,int size){
int i;
int j;
char* temp;
for(i=size/2;i>=0;i--)
percDown(array,i,size);
for(j=size-1;j>=1;j--){
temp = array[0];
array[0]=array[j];
array[j]=temp;
percDown(array,0,j);
}
}
void percDown(char** array,int i,int n){
int child;
char* temp;
for(temp=array[i];(2*i)+1<n;i=child){
child = 2*i+1;
if(child!=n-1&&strcmp(array[child],array[child+1])<0)
child++;
if(strcmp(temp,array[child])<0)
array[i] = array[child];
else
break;
}
array[i]=temp;
}
int main(void)
{
srand((unsigned)time(NULL));
int maxLength;
int numberOfStrings;
scanf("%d",&numberOfStrings);
scanf("%d",&maxLength);
const char *src = "abcdefghijklmnopqrstuvwxyz";
char** array;
array = (char**) malloc(numberOfStrings*sizeof(char));
int counter;
for(counter=0;counter<numberOfStrings;counter++){
array[counter] = random_fill(randomNum(maxLength), src);
puts(array[counter]);
}
heapSort(array,numberOfStrings);
for(counter=0;counter<numberOfStrings;counter++){
printf("%s \n",array[counter]);
}
char a;
scanf("%c",&a);
return 0;
}