Im trying to sort this random generated array, but my output isincorrect it looks like this:
sorted round: 0: 87
sorted round: 0: 78
sorted round: 0: 16
sorted round: 0: 94
sorted round: 0: 36
sorted round: 0: 93
sorted round: 0: 50
sorted round: 0: 22
sorted round: 0: 63
sorted round: 0: 28
sorted round: 0: 91
sorted round: 0: 60
sorted round: 0: 64
sorted round: 0: 27
sorted round: 0: 41
sorted round: 0: 73
sorted round: 0: 37
sorted round: 0: 12
sorted round: 0: 69
84
78
16
87
36
93
50
22
63
28
91
60
64
27
41
73
37
12
69 0
ive been at this for hours and havnt been able to figure out what im doing wrong, any help is appreciated.
#include <stdio.h>
#include <iostream>
#include <algorithm> // for std::find
#include <iterator> // for std::begin, std::end
using namespace std;
int main()
{
int random_array[20];
int i;
int j;
random_array[0]=rand()%(100-1 1) 1;
for (i=1; i<20;)
{
j= rand()%(100-1 1) 1;
bool exists;
exists = find(begin(random_array), end(random_array), j) != end(random_array);
if(!exists)
{
random_array[i]=j;
i=i 1;
}
else
{
;
}
}
int size=20;
i=0;
j=0;
int k =0;
for (i; i < size; i ) {
for (j; j < size - i; j )
{
for(k; k<20; k )
{
cout<<"sorted round: "<<j<<": "<<random_array[k]<<endl;
}
if (random_array[j] > random_array[j 1]) {
swap(random_array[j], random_array[j 1]);
}
else
{
;
}
}
}
for (i=0; i<20;i )
{
cout<<random_array[i]<<endl;
}
return 0;
}
The out put should be a sorted array called random_array and the issue im running into starts on this line of code:
int size=20;
i=0;
j=0;
int k =0;
for (i; i < size; i ) {
CodePudding user response:
In these nested for loops
for (i; i < size; i ) {
for (j; j < size - i; j )
{
for(k; k<20; k )
{
cout<<"sorted round: "<<j<<": "<<random_array[k]<<endl;
}
if (random_array[j] > random_array[j 1]) {
swap(random_array[j], random_array[j 1]);
}
else
{
;
}
}
}
neither variable j
nor the variable k
are reset to 0 in each iteration of the most outer loop
for (i; i < size; i ) {
At least you should write
for (i = 0; i < size; i ) {
for (j = 0; j < size - i; j )
{
for(k = 0; k<20; k )
{
cout<<"sorted round: "<<j<<": "<<random_array[k]<<endl;
}
if (random_array[j] > random_array[j 1]) {
swap(random_array[j], random_array[j 1]);
}
else
{
;
}
}
}
Pay attention to that the program invokes undefined behavior in the first iteration of the most outer loop that is when i
is equal to 0
because in this if statement
if (random_array[j] > random_array[j 1]) {
the expression random_array[j 1]
accesses memory beyond the array when j is equal size - 1
.
It is better to start the inner for loop with 1
for (j = 1; j < size - i; j )
{
and in if statement to write
if (random_array[j-1] > random_array[j]) {