Sort Ascending Random Numbers-Vectors

I'm trying to sort random numbers in ascending order and I was wondering how I should go about that.

Here's what I currently have.

#include <iostream>
#include <vector>
#include <cstdlib>
using namespace std;



int main(void)
{
cout << "Input a seed (int) to start the random number generator: ";
int seed;
cin >> seed;
srand(seed);

cout << "Input the minimum and maximum random int: ";
int minRange, maxRange;
cin >> minRange >> maxRange;

cout << "Input the length of the vector: ";
int vectorLength;
cin >> vectorLength;

vector<int> unsorted(vectorLength);
cout << " Vector beforehand: \t";
for (int i = 0; i < vectorLength; i = i + 1)
{ unsorted[i] = minRange + rand()%(maxRange - minRange + 1);
cout << unsorted[i] << " ";
}
cout << "\n";

////////////////////////////////////////////
int temp;

for(int i = 0; i < vectorLength; i = i + 1)
{
if(unsorted[i] > unsorted[i + 1])
{
temp = unsorted[i];
unsorted[i] = unsorted[i + 1];
unsorted[i + 1] = temp;
}
for(int j = 0; j < vectorLength; j = i + 1)
{
int minimum = unsorted[i];
if(minimum > unsorted[i])
{
minimum = unsorted[i];
}
else
{
unsorted[i] = minimum;
}

}
}
////////////////////////////////////////////

cout << " Vector afterhand: \t";
for (int i = 0; i < unsorted.size(); i = i + 1)
{ cout << unsorted[i] << " ";
}
cout << "\n";
}

return 0;
}


I'm trying to put our algorithm between the ////'s. We're only allowed to use for loops also. What I currently have is the minimum number finder and the use of temp to find the values. However, it doesn't seem to be working. I don't want you to do the program for me, but I'd appreciate it if someone can walk through some of the steps as to what I should do. And maybe look through what I have and see if there are any errors in there. Thanks :)
1
2
3
4
5
6
7
8
9
10
11
12
    for(int j = 0; j < vectorLength; j = i + 1)
    {
        int minimum = unsorted[i];
        if(minimum > unsorted[i])
        {
            minimum = unsorted[i];
        }
        else
        {
            unsorted[i] = minimum;
        }
    }


is equivalent to:

1
2
    for (int j=0; j<vectorLength; j = i+1 )
        ;


Note that if i+1 is less than vectorLength, you have an infinite loop.
Last edited on

and I was wondering how I should go about that


There are many approaches, though I think you should use one of the simplest:

Here I described very simple method called "Bubble Sort":

http://codeabbey.com/index/task_view/bubble-sort

Other variant is to select minimum element and swap it with the first, then select minimum of the remaining elements and swap it with the second etc. The procedure of choosing minimum you can practice here:

http://codeabbey.com/index/task_view/maximum-of-array
Last edited on
Topic archived. No new replies allowed.