#include <iostream>
#include <Windows.h>
void selection_sort(int*,int);
void output_array(int*, int);
int main() {
using namespace std;
int numbers[] = { 4, 6, 8, 2, 7, 5, 0,1, 3, 9 };
int length = 10;
selection_sort(numbers, length);
output_array(numbers, length);
Sleep(10000);
return 0;
}
void output_array(int* start, int length) {
for (int i = 0; i < length; i++) {
std::cout << *(start + i) << " ";
}
std::cout << std::endl;
}
void selection_sort(int* start, int length) {
for (int i = 0; i < length; i++) {
int max = *start;
int max_i = 0;
for (int j = 1; j < (length - i); j++) {
//find out the maximum
if (max < *(start + j)) {
max = *(start + j);
max_i = j;
}
}
//put it at the end
for (int k = max_i; k < (length - i -1); k++) { //The problem is HERE
*(start + k) = *(start + k + 1);
}
*(start + length - i) = max;
}
}
Perhaps it is a problem simple enough, but why when it comes to the last for loop, k is undefined? Is it because max_i is not a compile-time constant?
Variables
Program at this step
This doesn’t make sense to me.
When it comes to the second largest number, k behaves as expected.
>Solution :
void selection_sort(int* start, int length) {
for (int i = 0; i < length; i++) {
int max = *start;
int max_i = 0;
for (int j = 1; j < (length - i); j++) {
//find out the maximum
if (max < *(start + j)) {
max = *(start + j);
max_i = j;
}
}
//put it at the end
for (int k = max_i; k < (length - i -1); k++) {
*(start + k) = *(start + k + 1);
}
// The problem was here, you wanted to access memory that does not belong to you.
*(start + length - i - 1) = max;
}