#include <iostream>
using namespace std;
int main(){
int a[6] = {5, 2, 4, 6, 1, 3}; // create an array of size 6
int j, key = 0;
for (int i = 1; i < 6; i++) {
key = a[i];
j = i - 1;
while ((j >= 0) && (a[j] > key)) {
a[j + 1] = a[j];
j -= 1;
}
a[j + 1] = key;
}
for (int l = 0; l < 6; l++) {
cout << a[l];
}
return 0;
}
I'm trying to test my insertion sort code using an array the code complies but when I try to execute the a.out file, it gives me "Segmentation Fault", I look up what segmentation fault is, it's basically an error that we are trying to access the forbidden memory location, however, I'm wondering where exactly is the error in my code. Also, if i get rid of the
for (int l = 0; l < 6; l++) {
cout << a[l];
}
no error is found.
jis not initialized. This may not be the cause of your problem, but it's still bad practice.