Sort algorithm for integers

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.

I would suggest using a debugger to go step through your code and check what it is doing. Btw, lines 5-7 can be turned into:
 
std::swap(list[j-1], list[j]);


In relation to your vectorSort(), yes, that is usually how you would do it.
Thanks for the reply. It appears I have solved both issues - after stepping through the debugger as you suggested.

The problem seems to have been in my 'swap' algorithm. The one that works with negative numbers 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];
			list[j] = list[j - 1];
			list[j - 1] = temp;
		}
		i++;
	}
}
Topic archived. No new replies allowed.