Hi there. I wrote a Cocktail Sort algorithm, and am testing it by generating random vectors of size 500 up to 10,000 - running it 10 times per vector. After about the 2000-3000 length vector mark, the code segfaults. I expect it isn't the test code as the same test is used for multiple sorting algorithms and it runs fine for every other algorithm. I am assuming somewhere I miss an end-condition and it tries to access an element of the input array that doesn't exist... but I'm not entirely sure if that would cause a segfault to be run.
This is the code, I hope someone can spot my error. (I also would enjoy any comments on how it could be better - but please note I do value readability over speed for this code.)
void Sorting::cocktailSort(vector<int>& A) {
int temp;
// The first/last indexes to check. Anything before/after these indexes
// is already sorted.
int firstIndex = -1;
int lastIndex = A.size()-1;
bool swapped;
do {
firstIndex += 1;
swapped = false;
for(int i = firstIndex-1; i < lastIndex; i++) {
if(A[i] > A[i+1]) {
temp = A[i];
A[i] = A[i+1];
A[i+1] = temp;
swapped = true;
}
}
if(!swapped) break;
swapped = false;
lastIndex -= 1;
for(int i = lastIndex; i >= firstIndex; i--) {
if(A[i] < A[i-1]) {
temp = A[i];
A[i] = A[i-1];
A[i-1] = temp;
swapped = true;
}
}
}while (swapped);
}
This is not homework.