Sort a list of numbers using a random number generator function
  • Posted: 3 years ago
  • Edit
  • answers (1)
  • views (1871)

Suppose you are given a list of numbers and a function random(0,1) that returns a random integer between 0 and 1 . Write an algorithm to sort the given list based on the output of the function random(0,1) . Assume that this function is called once for every number on the list.


Posted Answers




void sortArray(float input[], int length)
{
float sum = 0;
float num;
srand(time(0));
float output[length];
cout < < "ArraySize: " < < < endl;
cout < < "Arrya before sorting: " < < endl;
for (int i = 0; i < length; i++)
cout < < "Value at index " < < i < < ": " < < input[i] < < endl;

for (int i = 0; i < length; i++)
{
num = (rand()/(float)RAND_MAX);
output[i] = sum = input[i] - num;
}

sum = sum - (rand()/(float)RAND_MAX);
for (int i = 0; i < length; i++)
output[i] = output[i]/sum;

for (int i = 0; i < length; i++)
{
float temp;
for (int j = i+1; j < length; j++)
{
temp = output[i] - output[j];
if (temp > 0)
{
float tempnum = input[i];
input[i] = input[j];
input[j] = tempnum;

tempnum = output[i];
output[i] = output[j];
output[j] = tempnum;
}
}
}
cout < < < "==========================================" < < < "Arrya after sorting: " < < endl;
for (int i = 0; i < length; i++)
cout < < "Value at index " < < i < < ": " < < input[i] < < endl;
}


You need to Sign In to post your solution.