void InsertionSorting( int numberarray[] , int numberOfsize ){
int temp , j ;
numberarray[ 0 ] = 8;
for( int i = 1 ; i <= numberOfsize ; i++ ){
temp = numberarray[ i ];
j = i - 1;
while( temp < numberarray[ j ]){
numberarray[ j + 1 ] = numberarray[ j ];
j--;
}
numberarray[ j + 1 ] = temp;
}
}
1 2 3 4 5
int main(){
int choice = 0;
//array automatically pass by reference
int numbers[] = { 8 , 20 , 11 , 82 , 90 , 2 , 32 , 49 , 77 , 41 , 23 , 17 };
1 2 3 4
InsertionSorting( numbers , 12 );
cout << "\nAscending order for Insertion Sort function : " << endl;
for ( int i = 1 ; i <= 12 ; i ++ )
cout << numbers[i] << " " ;
GET an error code said my numbers variable are corrupted . can someone tell me while?
This kind of error will often come up when an index is off by 1 (given that the code logic is correct).
This looks off by 1 because 'numbers' has 12 elements that count from numbers[0] and end at numbers[11]. This loop has iterates over 12 elements but starts at numbers[1] and at the end it is attempting to access element numbers[12] which does not exist. for( int i = 1 ; i <= numberOfsize ; i++ )
for( int i = 0 ; i < numberOfsize ; i++ ) //this is the correct range
line 9 will be a new problem though since when i == 1 then j == -1 which again will be out of range...
that's why i having the problem at here , although change the loop but still cant get the result that i want..
the last numbers[i] will be shown in -878237
something like this
InsertionSorting( numbers , 12 );
cout << "\nAscending order for Insertion Sort function : " << endl;
for ( int i = 0 ; i < 12 ; i ++ ) //range needs to be changed here too or u'll
//be printing garbage and will think u made a mistake in the sorting algorithm...
cout << numbers[i] << " " ;
//this is in descending order so that you can figure out how to make it ascending :D
//it's just a matter of having i-- and j-- and reversing the boundary checks on numberarray
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
void InsertionSorting( int numberarray[] , int numberOfsize )
{
int temp = numberarray[0];
for(int j=0; j<1; j++) //number of rotations - currently set to 1
{
for( int i = 0 ; i < numberOfsize ; i++ ) //rotate all elements by 1
{
if(i == numberOfsize-1) //if this is the boundary of the range
{
numberarray[i] = temp;
temp = numberarray[0];
}
else
{
numberarray[ i ] = numberarray[ i + 1 ];
}
}
}
}