Skip to content

Instantly share code, notes, and snippets.

@RDharmaTeja
Created December 13, 2014 17:32
Show Gist options
  • Save RDharmaTeja/38333dd5da75fa61892c to your computer and use it in GitHub Desktop.
Save RDharmaTeja/38333dd5da75fa61892c to your computer and use it in GitHub Desktop.
/* Bubble sort implementation in C */
#include<stdio.h>
/* swapping two elements by reference */
void swap(int *a,int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
/* print array */
void printArray(int A[], int N)
{
int i=0;
for (i = 0; i < N; ++i)
{
printf("%d ",A[i]);
}
}
/* bubble sort implementation */
void bubbleSort(int A[], int N)
{
int i,j;
int swapped;/* check if there is swap in a traversing*/
for (i=0; i < N; ++i)
{
swapped = 0;
for (j=0; j < N-i-1; ++j)
{
/*
travase once through the array with swapping, max value
in resultant array will be in the highest index i.e. in
next traversing we have to sort only first n-1 indices
*/
if (A[j]>A[j+1])
{
swap(&A[j],&A[j+1]);
swapped = 1;
}
}
/* No swap */
if(swapped==0)
{
break;
}
}
}
int main()
{
int T,N;
int i,j;
int A[200];
scanf("%d",&T);
for (i=0; i < T; ++i)
{
scanf("%d",&N);
for(j=0; j < N; ++j)
{
scanf("%d",&A[j]);
}
bubbleSort(A,N);
printArray(A,N);
printf("\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment