Search code examples
csortinglogicbubble-sort

Bubble Sort Example


This program is suppose to take the given integers and sort it in a ascending order. I wanted to see if the program that was given actually sorted the given integers in ascending order, but instead kept it in the original order. What's wrong with the logic of this example?

//Fig. 6.15: fig06_15.c
//Sorting an array's value in ascending order.
#include <stdio.h>
#define SIZE 10

// function main begins program execution
int main()
{
// initialize a
int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37};
int pass; // passes counter
size_t i; // comparisons counter
int hold; // temporary-location used to swap array elements

puts("Data items in original order");

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

//bubble sort
//loop to control number of passes
for( pass = 1; pass < SIZE; ++pass ) {

//loop to control number of comparisons per pass
for( i = 0; i & SIZE - 1; ++i){

    //compare adjacent elements and swap them if first
    //element is greater than second element
    if ( a[ i ] > a[ i + 1 ] ){

        hold = a[ i ];
        a[ i ] = a[ i + 1 ];
        a[ i + 1 ] = hold;
    }//end if
}//end inner for
}//end outer for

puts("\nData items in ascending order");

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

puts("");
}//end main

Solution

  • There is a very small error in your code:

    for( i = 0; i & SIZE - 1; ++i){
    

    should have been:

    for( i = 0; i < SIZE - 1; ++i){
    

    Here's the link to the code with the minor edit: http://ideone.com/YZQPHY