So I'm making a selection sort program where I have to input two values: one for the numbers to use in the array, and the seed to use for the random number generator. I'm just a little confused on how to adjust the number used, since the maximum number of elements we can put in is 15. The array currently has 8. Each element should be a number between 20 and 40.
#include <iostream>
using namespace std;
int selectionSort(int[], int);
int 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 - 1; ++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;
}
return indexSmallest;
}
int main() {
int numbers[] = {10, 2, 78, 4, 45, 32, 7, 11};
const int NUMBERS_SIZE = 15;
int i = 0;
int nums = 0;
int seed = 0;
cin >> nums;
cin >> seed;
srand(seed);
for (int i = 0; i < nums; i++) {
numbers[i] = (rand() % 20) + 20;
}
cout << "UNSORTED: ";
for (i = 0; i < NUMBERS_SIZE; ++i) {
cout << numbers[i] << " ";
}
cout << endl;
selectionSort(numbers, NUMBERS_SIZE);
cout << "SORTED: ";
for (i = 0; i < NUMBERS_SIZE; ++i) {
cout << numbers[i] << " ";
}
cout << endl;
}
When I input "10 100" (10 being the numbers to use in the array and 100 being the seed), I get this in the output screen:
UNSORTED: 25 36 35 24 24 34 38 22 29 29 5634432 10498254 1 8896376 8876856
SORTED: 1 22 24 24 25 29 29 34 35 36 38 5504116 5785352 5787344 15085774
with the error in the code: Exception thrown at 0x0F45FBA0 (ucrtbased.dll) in Project11.exe: 0xC0000005: Access violation reading location 0x00BF9640.
I'm betting this has something to do with the size of the array, since the original size is only 8 but we're using 10 numbers from the array, so the last two are null. How can I change the array input so each value is put in correctly?
You write past the end of numbers, resulting in Undefined Behavior (in this case, overwriting the stack and possibly altering the return address).
Your SORTED output is garbage because of a typo in your cout statement.
User contributions licensed under CC BY-SA 3.0