Switching random numbers
I'm getting an error saying that "i" in "int numbers[i]..." is unidentified. I'm not sure how to fix it.
The original problem is to write a program that implements a selection sort, using 8 random numbers between 1 and 100.
Sample Output:
UNSORTED: 10 2 78 4 45 32 7 11
SORTED: 2 4 7 10 11 32 45 78
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
#include <iostream>
#include <random>
#include <ctime>
#include <cstdlib>
using namespace std;
void SelectionSort(int numbers[], int numbersSize) {
int i = 0;
int j = 0;
int indexSmallest = 0;
int temp = 0; // Temporary variable for swap
for (i = 0; i < numbersSize; ++i) {
// Find index of smallest remaining element
indexSmallest = i;
for (j = i + 1; j < numbersSize; ++j) {
if ( numbers[j] < numbers[indexSmallest] ) {
indexSmallest = j;
}
}
// Swap numbers[i] and numbers[indexSmallest]
temp = numbers[i];
numbers[i] = numbers[indexSmallest];
numbers[indexSmallest] = temp;
}
}
int main() {
//Random number
srand((unsigned int)time(NULL));
int numbers[i] = rand() % 100 + 1;
const int numbersSize = 8;
int i = 0;
cout << "UNSORTED: ";
for (i = 0; i < numbersSize; ++i) {
cout << numbers[i] << ' ';
}
cout << endl;
SelectionSort(numbers, numbersSize);
cout << "SORTED: ";
for (i = 0; i < numbersSize; ++i) {
cout << numbers[i] << ' ';
}
cout << endl;
return 0;
}
|
Move line 36 directly after line 41 (without the type int
)
After line 37: int numbers[numbersSize];
Last edited on
morning.
You can't do this:
int numbers[i] = rand() % 100 + 1;
even if you were to define i.
You need to populate your numbers array in exactly the same way as you are printing out it's contents, e.g.
1 2 3
|
for (i = 0; i < numbersSize; ++i) {
numbers[i] = < create a random number here and assign to the ith element in the array >
}
|
edit:
and declare your array like this:
1 2
|
const int numbersSize = 8;
int numbers[numbersSize];
|
Last edited on
Topic archived. No new replies allowed.