I'm brand new to C++ and am trying to write this simple selection sort function. Apologies if the answer is simple to the more experienced coders, but I am beginner and have been staring at this for a long time to no avail. Here is my code:
#include <iostream>
#include <array>
using namespace std;
array<int, 10> unsorted {3, 4, 1, 5, 7, 2, 8, 9, 6, 0};
void printarray(array<int, 10> arr) {
int count = 0;
for (int i : arr) {
if (count < arr.size()-1) {
cout << i << ", ";
} else {
cout << i << endl;
}
count++;
};
}
int selection_sort(array<int, 10> arr) {
int test;
array<int, 10> newarr;
for(int j = 0; j < arr.size(); j++) {
test = arr[j];
for(int i = j; i < arr.size(); i++) {
if(arr[i+1] < test) {
test = arr[i];
}
}
newarr[j] = test;
}
printarray(newarr);
return 0;
}
int main() {
selection_sort(unsorted);
return 0;
}
When I run this function it prints an int array containing 10 zeros. Is there an error with the way I am assigning values to the array (in C++), or rather is there a problem with the logic itself?
arr? If the smallest value is at the end ofarrit will be copied into every elementmain()function that illustrates how you call theselection_sort()function.if(arr[i+1] < test). Whenireaches its maximum value ofarr.size()- 1,arr[i+1]will be out of bounds.