Hello, I wrote a simple sorting algorithm that sorts an array of integers into increasing order. The sort algorithm is:
1 2 3 4 5 6 7 8 9 10 11
|
void sort( int list[], int length ) {
int i = 1;
while ( i < length ) {
for ( int j = i; list[j - 1] > list[j]; j-- ) {
int temp = list[j - 1];
list[j - 1] = list[j];
list[j] = temp;
}
i++;
}
}
| |
This seems to work for arrays within about 15 elements in length. I am calling the sort function like this:
sort( list, length );
where the list and length variables are initializes as:
1 2
|
int list[] = { 2, 3, 4, 2, 5, 3, 8, 3, 4, 33, 44, 9, 9, 9, 9 };
int length = sizeof(list) / sizeof(int);
| |
This appears to be working correctly until I add more integers to the array, causing the length to be close to or above 25 elements. The program starts to run, then prints out garbage, and crashes.
I have searched on topics like this and have heard that the 'sizeof(list)/sizeof(int)' method of getting size 'magically fails' when used in function calls because of how pointers work. I understand that passing int list[] as a paramater is the same as passing the address of the first element in list. I have also checked to see that
cout << length;
inside the sort function prints out the correct length (the same length as is calculated outside the function, as I pass just the int value of length to the function).
Why does this work only when the array is under ~25 elements in length? (Also noticed there is a problem when negative numbers are used in the array, but I assume that is a logic error in my algorithm that I will work out later).
*I have also considered using vectors to hold the list of integers, and to sort those, but am having problems passing vectorSort( vector<int>& vect ) as a parameter. Is this what I should be doing? Thanks for taking the time to read and respond.