Hello,
I've been charged with the following task:
•Write a program that:
•1) Creates an array containing 1000 random double numbers in the [0,250) range;
•2) Sorts them in ascending order;
•3) Prints the contents of the sorted vector out. The sorting should be coded as a separate function double* sort_array(double* ).
I had gotten stuck and referred to help from other forum postings, but I'm still having trouble. I'm not quite sure how to put the sorting in another function. I tried, but if anyone can point out what I did wrong, your help is greatly appreciated. With the following code, I'm currently getting the error messages:
line 41: error: unexpected '(' for function style cast or type construction
line 41: error: use of undeclared identifier 'MyArray'
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
//program to sort array
double* sort_array(double* MyArray)
{
//Bubblesort code in ascending order
double size =1000;
int a, b, t;
for (a=1; a<size; a++) { //
for (b=size-1; b>=a; b--) { //
if (MyArray [b-1] > MyArray [b]) { //if not in ascending order
//exchange elements
t = MyArray [b-1]; //use t as a placeholder so original value of MyArray [b-1] is not lost
MyArray [b-1] = MyArray [b]; //change value of MyArray [b-1] to value of MyArray [b]
MyArray [b] = t; //change value of MyArray[b] to value of placeholder aka original value of MyArray [b-1]
}
}
}
return MyArray; //returns sorted values
}
//main program, creates array
int main()
{
srand(time(NULL)); //generate random numbers based on time
int t;
double size = 1000;
double unsort[1000]; //creates array of 1000 double values
for (t=0; t<size; ++t) //check boundaries, use size for 1000
{
unsort[t] = (double)(rand()%251); //assign random double numbers between [0,250]
cout << unsort[t] << " "; //print unsorted values
}
cout << "\n" << endl;
sort_array(double* MyArray);
for (t=0; t<size; t++){
cout << unsort[t];
}
return 0;
}
|
Time is of the essence, so thank you in advance for any quick suggestions!