-1

When I try to generate random values for various sorting algorithm to gprof them and compare the results, I noticed the random() function was creating same values within an instance and in same order. Is there a way to get rid of it?

Example I tried profiling bubble sort and so randomly created 10000 values and bubble sorted it, now again when I give 10000 values its generating same set of values as before and in the same order.

When I changed the value to 1000 the first 1000 values of previous test were exactly same as this case. I changed the range of values with different possibilities like only positive integers and both positive, negative integers. What is the reason random() function is generating same values? And is there a way to fix it?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
nt fury
  • 39
  • 1
  • 9

1 Answers1

1

When you are using random you need to provide a seed otherwise you will always get the same result. A common seed to use is the current time.

As seen here: How to generate a random number in C?

#include <time.h>
#include <stdlib.h>

srand(time(NULL));   // should only be called once
int r = rand();      // returns a pseudo-random integer between 0 and RAND_MAX
Nick Chapman
  • 4,402
  • 1
  • 27
  • 41