Hello everyone, today's C code snippet is about bubble sorting. Bubble sort is the easiest way to sort a collection of numbers. It works by sequentially going through the array and comparing two consecutive values at a time, swapping them if necessary. Then, the process is repeated until no swaps are required.

Additionally, our code detects the same values in an array and removes the repeated values. For example, 

{2,4,6,2,5,2,3,1} will be sorted as {1,2,3,4,5,6}.

* Author : Berk Soysal

#include <stdio.h>
#include <stdlib.h>
#define N 10

void sort(int *a, int n)
    int k, j, temp;

    for(k=0; k<n-1; k++)
        for(j=0; j<n-1; j++)
    // If the previous value is larger, swap.
            if( a[j]>a[j+1] )
                temp = a[j];
                a[j] = a[j+1];
                a[j+1] = temp;
    // If there are any equal values, keep only one nonzero
            else if(a[j]==a[j+1])

int main()
    int i, x[N] = {42,12,53,86,27,70,64,70,45,23};

    // Print the input
    printf("Input : ");
    for(i=0; i<N; i++)


    // Call the sort function
    sort(x, N);

    // Print the sorted array
    printf("Sorted: ");
    for(i=0; i<N; i++)


    return 0;


Please leave a comment if you have any questions or comments. 

Keywords: CCode Snippets

Software Developer, Codemio Admin

Disqus Comments Loading..