I guess that what you want is a descending sort algorithm, but in the case of Fibonacci numbers you can take advantage that they are already sorted at the beginning. Here are different strategies that you can try :
/*
SORTING IN DESCENDING ORDER
*/
const int nbElem = 15; // 24 max
int fibonacci[ nbElem ] = { 0, 1 };
void createFibonacciArray( int inputArray[], int arraySize )
{
fibonacci[ 0 ] = 0;
fibonacci[ 1 ] = 1;
for( int i=0; i<nbElem-2; i++ )
fibonacci[ i+2 ] = fibonacci[ i ] + fibonacci[ i+1 ];
}
void displayArray( int inputArray[], int arraySize )
{
for( int i=0; i<arraySize; i++ )
Serial.println( inputArray[ i ] );
}
void displayArrayReverse( int inputArray[], int arraySize )
{
for( int i=arraySize-1; i>=0; i-- )
Serial.println( inputArray[ i ] );
}
void reverseArray( int inputArray[], int arraySize )
{
for( int i=0; i<nbElem/2; i++ )
{
int fTemp = fibonacci[ i ];
fibonacci[ i ] = fibonacci[ nbElem-i-1 ];
fibonacci[ nbElem-i-1 ] = fTemp;
}
}
void inverseBubbleSort( int inputArray[], int arraySize )
{
for( int i=0; i<arraySize-1; i++ )
{
for( int j=0; j<arraySize-1-i; j++ )
{
if( inputArray[ j ] < inputArray[ j+1 ] )
{
int temp = inputArray[ j+1 ];
inputArray[ j+1 ] = inputArray[ j ];
inputArray[ j ] = temp;
}
}
}
}
void bubbleSort( int inputArray[], int arraySize )
{
for( int i=0; i<arraySize-1; i++ )
{
for( int j=0; j<arraySize-1-i; j++ )
{
if( inputArray[ j ] > inputArray[ j+1 ] )
{
int temp = inputArray[ j+1 ];
inputArray[ j+1 ] = inputArray[ j ];
inputArray[ j ] = temp;
}
}
}
}
void setup()
{
Serial.begin( 115200 );
// Create and display Fibonacci array
createFibonacciArray( fibonacci, nbElem );
Serial.print( "\n\nFIBONACCI ARRAY\n" );
Serial.print( "===============\n" );
displayArray( fibonacci, nbElem );
// Solution 1: Display array starting from the end
Serial.print( "\n\nFIBONACCI ARRAY STARTING FROM THE END\n" );
Serial.print( "=====================================\n" );
displayArrayReverse( fibonacci, nbElem );
// Solution 2: Reverse array
reverseArray( fibonacci, nbElem );
Serial.print( "\n\nFIBONACCI REVERSED ARRAY\n" );
Serial.print( "========================\n" );
displayArray( fibonacci, nbElem );
// Solution 3: Inverse bubble sort array
createFibonacciArray( fibonacci, nbElem );
inverseBubbleSort( fibonacci, nbElem );
Serial.print( "\n\nFIBONACCI SORTED IN DESCENDED ORDER WITH BUBBLE SORT\n" );
Serial.print( "====================================================\n" );
displayArray( fibonacci, nbElem );
// Ascending order sort array
bubbleSort( fibonacci, nbElem );
Serial.print( "\n\nFIBONACCI SORTED WITH BUBBLE SORT\n" );
Serial.print( "=================================\n" );
displayArray( fibonacci, nbElem );
}
void loop()
{}
14
is the lasti
index, but you are still reading fromi+1
and writing toi+2
. You should fix your bounds.