sorting rand arr[]

Hi C++ ;
I have 5 random arr; how can I sort this 5 random numbers
from less to high ?
Thanks;

1
2
3
4
5
6
7
8
9
10
11
int n[4];

for (int i = 1; i < 6; i++)
 {
  cout << " line " << i + 1 << " :    ";
  cout << n[0] + (rand() % 15) << " ";
  cout << n[1] + (rand() % 15) << " ";
  cout << n[2] + (rand() % 15) << " ";
  cout << n[3] + (rand() % 15) << " ";
  cout << n[4] + (rand() % 15) << " " << endl;
}
Last edited on
> int n[4];
Start by making sure you have space for 5.

Then https://www.cplusplus.com/reference/algorithm/sort/
Second, your have to actually store the random numbers in the array before you can sort it.

Lines 6-9: You appear to be printing uninitialized members of the array.

Line 10: As salem c pointed out, n[4] is out of bounds.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
   const int N = 5, MX = 15;
   int A[N];
   srand( time( 0 ) );
   for ( int i = 0; i < N; i++ )
   {
      int value = rand() % MX;
      int j = i;
      for ( ; j > 0 && A[j-1] > value; j-- ) A[j] = A[j-1];
      A[j] = value;
   }
   for ( int i = 0; i < N; i++ ) cout << A[i] << ' ';
}
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
#include <iostream>
#include <random>
#include <algorithm>

auto Rand {std::mt19937 {std::random_device {}()}};

int main()
{
	const size_t maxNo {15};
	const size_t noReq {5};

	auto randNo {std::uniform_int_distribution<int> {0, maxNo}};

	int n[noReq] {};

	for (auto& no : n)
		no = randNo(Rand);

	std::sort(std::begin(n), std::end(n));

	for (const auto& no : n)
		std::cout << no << "  ";

	std::cout << '\n';
}

the idiotic lazy way (a specialty of mine, I think 2 of my professors retired right after I was in their class).

something like...
int n[5];
n[0] = rand() % maxval*0.2;
n[1] = n[0] + rand()%maxval*0.2;
n[2] = n[1] + ... etc

yes, its blatant cheating. Sometimes, depending on the true requirement, blatant cheating is the correct solution. Other times, it really isnt. But its "an" answer. You eliminate the need to sort by generating them in assured sorted order. if the quality of the randomness is not important, its good enough for many a problem.
Last edited on
Topic archived. No new replies allowed.