# c program - array - need help

Hello,

i'm trying to modify the bubble sort of the below program but i just don't get how to do it. This is driving me mad:-((

I think I have spent so much time on this exercise that i'm not able to think clearly anymore...

"The data in the array may already be in the proper order or near proper order, so why make nine passes if fewer will suffice? Modify the sort to check at the end of each pass whether any swaps have been made. If none has been made, then the data must already be in the proper order, so the program should terminate. If swaps have been made, then at least one more pass is needed."

Here is the code

[code]/* Program that modifies the bubble sort array in fig. 6.15 */

#include
#define SIZE 10

int main ( void )
{
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; /* declare and initialize array a */
int pass; /* passes counter */
int i; /* comparisons counter */
int hold; /* temporary location used to swap arrays elements */
int NumOfComparisons = 0;

printf( "Data items in original order:

" );

for ( i = 0; i < SIZE; i++ ){ /* display array output */
printf( "%4d", a[ i ] );
} /* end of for loop */

/* bubble sort */
for ( pass = 1; pass < SIZE; pass++ ){
for ( i = 0; i < SIZE - 1; i++ ){
if ( a[ i ] < a[ i + 1] ){
break;
}

else if ( a[ i ] > a[ i + 1] ){
hold = a[ i ];
a[ i ] = a[ i + 1];
a[ i + 1] = hold;
pass++;
}/* end of if */

NumOfComparisons = NumOfComparisons + 1;

}/* end of inner for */

}/* end of outer for */

printf( "
Data items in ascending order:

" );

for ( i = 0; i < SIZE; i++ ){ /* output array in ascending order */
printf( "%4d", a[ i ] );
}

printf( "

" );

printf( "Number of comparisons: %d
", NumOfComparisons );

return 0;
}[/code]

• [code]
/* Program that modifies the bubble sort array in fig. 6.15 */

#include
#define SIZE 10

int main ( void )
{
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 }; /* declare and initialize array a */
int pass; /* passes counter */
int i; /* comparisons counter */
int hold; /* temporary location used to swap arrays elements */
int NumOfComparisons = 0;
[red]int SwapCount ;[/red]

printf( "Data items in original order:

" );

for ( i = 0; i < SIZE; i++ ){ /* display array output */
printf( "%4d", a[ i ] );
} /* end of for loop */

for (pass = SIZE - 1 ; pass > 0 ; [red]pass--[/red]) {
[red]SwapCount = 0 ;[/red]
for (i = 0 ; i < pass ; i++) {
NumOfComparisons++ ;
if (a[i] > a[i + 1]) {
hold = a[i] ;
a[i] = a[i + 1] ;
a[i + 1] = hold ;
}
}
[red]if (SwapCount == 0)
break ;[/red]
}

printf( "
Data items in ascending order:

" );

for ( i = 0; i < SIZE; i++ ){ /* output array in ascending order */
printf( "%4d", a[ i ] );
}

printf( "

" );

printf( "Number of comparisons: %d
", NumOfComparisons );

return 0;
}
[/code]
• Thank you so much!!!:-D

raeiko