hello, I'm trying to write a version of bubble sort with some
improvement.
One of these is that at the end of every pass, the algorithm
compare the array before and after the bubble sort; if they are
equal it stops; otherwise it execute bubble sort again
Code:
#include <stdio.h>
#include <assert.h>
void bubble_sort(int array[], int array_length);
void print_array(int array[], int array_length);
int are_different(int array_a[], int array_b[], int common_length);
int main( void )
{/*************/
int a[] = {3,1,4,2};
print_array(a,4);
bubble_sort(a,4);
print_array(a,4);
return 0;
}
void bubble_sort(int array[], int array_length)
{/********************************************/
int pass; /* pass counter */
int i; /* vector index */
int hold; /* temporary location */
/* A copy of the original array for future
* comparison with modified versions */
int orig_array[array_length];
for ( pass = 1; pass < array_length; pass++ )
{
for ( i=0 ; i < array_length; i++ )
orig_array[i] = array[i];
/* here the first change, with 1 substitueted by pass,
in order to diminish the comparison with pass
increasing*/
for ( i = 0; i < array_length - pass; i++ )
{
if ( array[ i ] > array[ i + 1 ] )
{
hold = array[ i ];
array[ i ] = array[ i + 1 ];
array[ i + 1 ] = hold;
}
}
/* here the decision to continue or not, based on
"modified" dummy */
assert(are_different(orig_array, array, array_length));
if (are_different(orig_array, array, array_length))
/* if modified execute it again */
continue;
else
break; /* if not modified exit */
}
}
int are_different(int array_a[], int array_b[], int common_length)
{/***************************************************************/
int i;
for (i = common_length -1; i = 0; i--)
{
if (array_a[i] != array_b[i])
return 1;
}
return 0;
}
void print_array(int array[], int array_length)
{/********************************************/
int index;
for (index = 0; index < array_length ; index++)
printf("%3d ", array[index]);
printf("\n");
}
I can't get are_different(orig_array, array, array_length) to be 1, and don't see why
Code:
$: ./a.out
3 1 4 2
a.out: bubble_sort.c:63: bubble_sort: Assertion `are_different(orig_array, array, array_length)' failed.
Aborted