Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,166 questions

40,722 answers

573 users

How to implement bubble sort in C

1 Answer

0 votes
#include <stdio.h>

void print_array(int arr[], int size);
 
int main(void)
{
    int i, j, tmp, size, swap, a[7] = {1, 2, 3, 4, 5, 7, 6};
    size = sizeof(a) / sizeof(int);
    
    for(i = 0; i < size; i++)
    {
        swap = 0;
        for(j = 0; j < size - i - 1; j++)
        {
            if(a[j] > a[j + 1])
            {
                tmp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = tmp;
                
                swap = 1;
            }
        }
        // if swap is 0 we didn't swap nothing, the array is sorted, we stop the loops
        if (swap == 0) break; 
    }
    
    print_array(a, size);
 
    return 0;
}
 
void print_array(int arr[], int size)
{
    int i;
    
    for (i = 0; i < size; i++)
         printf("%3d", arr[i]);  
} 




answered Apr 13, 2014 by avibootz
edited Sep 11, 2014 by avibootz

Related questions

1 answer 59 views
1 answer 53 views
1 answer 34 views
1 answer 45 views
1 answer 41 views
...