Hi!
The goal of this program is to let the user enter a number, then create as many random numbers as the user entered (the random numbers must be between 1 - 1 000 000). And then the program has to sort those random numbers into an ascending order. Here's what I have so far.
Yeah, I've heard of bubble sort, but I don't really know how to implement it here. I basically know the algorithm, but don't exactly know where and how to put it.
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <vector>
usingnamespace std;
int main()
{
//needed for sort function
vector<int> elements;
int numElements;
cout << "Enter number: \n";
cin >> numElements;
srand(static_cast<unsignedint>(time(0)));
cout << "Random numbers: \n";
for(int i = 0; i < numElements; i++){
elements.push_back((rand()%1000000) + 1);
cout << elements[i] << ",";
if(i == numElements){
cout << "i";
}
}
cout << '\n' << "the vector sorted is: ";
//sorts the vector
sort(elements.begin(), elements.end());
//output
for(int i = 0; i < elements.size(); i++){ cout << elements[i] << ",";}
cin.ignore(); // no system commands here
return 0;
}
there is also bubble sort which is
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void floatingSort(int *array)
{//length is the length of the array you want sorted
int i,j;
for(i=0;i<length;i++)
{
for(j=0;j<length;j++)
{
if(array[i]>array[j])
{
int temp=array[i]; //swaps the value
array[i]=array[j];
array[j]=temp;
}
}
}
}
Wait, I got the code a little bit better. It now shows the numbers in an ascending order, but also adds 1 random number at the end. How to get rid of it?
And also how can I get a random number between 1 and 1 000 000? Right now it seems it wont get higher than 30 000 or so..
I'm really, really thankful for all the help!
The rand() function generates a random number from 0 to RAND_MAX, which is only 32767 for me.
So if you want a random number from 1 to 1 million, you're going to have to use a different pseudo-random number generator....
Also, what's the point of this line? numElements <= MAX_SIZE;
I think you meant to check that numElements is less than or equal to MAX_SIZE, and do something (e.g. print an error or something) if it's not, but right now that line of code does absolutely nothing.
Anyways: for(int i = 0; i <= numElements; i++){ // Should be < , not <=
that's your problem. (I think -- I haven't tested this myself, but I'm pretty sure about it)