### Whats wrong with this code?

Hi, this algorithm is not working, i am trying to sort random numbers generated by the program, then using bubble sort to sort them. When the code runs i get negative numbers that are out of my range, which should not happen. I am asking the program to generate 5 numbers between 1 and 5.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051`` ``````#include #include using namespace std; void bubble_Sort(int arr[], int n); int main() { int arr[1000]; int array; int low, high; int random_integer; srand((unsigned)time(0)); ///// random number generator cout<<"How Many Numbers would you like to Generate"<< endl; cin>> array; cout<<"What is the lowest number of your range: "; cin>>low; cout<<"What is the highest number of your range: "; cin>>high; int range=(high-low)+1; cout<<" Your Random Numbers to be sorted are: "<< endl; for (int i =0; i < array; i++) { arr[i] = random_integer = low+int(range*rand()/(RAND_MAX + 1.0)); cout << arr[random_integer] << ", "; } bubble_Sort( arr, array); //cin>>arr[int i]; cout << endl; cout<<"Your Sorted numbers are: \n"; for (int i =0; i < array; i++) cout< arr[j+1]) { int tmp = arr[j+1]; arr[j+1] = arr[j]; arr[j] = tmp; } }``````

The Plan of this program is that the user can decided how many numbers can be generated and the range of these numbers, then its sorted using the bubble sort

Thanks
Michael
Last edited on
Think you find i have stated what the error is, that my program program is generating negative numbers.
 ``12345`` `````` for (int i =0; i < array; i++) { arr[i] = random_integer = low+int(range*rand()/(RAND_MAX + 1.0)); cout << arr[random_integer] << ", "; //possible out of bounds (makes no sense, really) }``````
im still very new to C++ and i have found this is the hardest thing i have en-counted so far, do you know how this problem can be corrected?
Do one thing, and do it right
 ``123456789101112131415161718192021`` ``````int rand(int low, int high){ //not verified int range = high-low; return low+range*(rand()/((double)RAND_MAX)); } void print(int *array, int size){ for(int K=0; K
Last edited on
Thank you, how did add this/replace this in parts of the program i added it and got errors saying that the array_size was unidentified.

Thanks i really appreciate it
`array_size' contains the size of the array.
You do have some variable that does that, it's called `array' (a terrible name, so I change it)

However, that's not important, ¿don't you get the idea?
first fill your array, then print it.
yeah i understand the idea, but i just cant seem to get your code working with mine.
Topic archived. No new replies allowed.