Skip to content

Instantly share code, notes, and snippets.

@RDharmaTeja
Created December 14, 2014 06:34
Show Gist options
  • Save RDharmaTeja/1eb06438823dd21ab4d9 to your computer and use it in GitHub Desktop.
Save RDharmaTeja/1eb06438823dd21ab4d9 to your computer and use it in GitHub Desktop.
/* insertion 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]);
}
}
/* insertion sort function */
void insertionSort(int A[], int N)
{
int i,j;
for (i = 1; i < N; ++i)
{
for (j = i-1; j >=0 ; --j)
{
/* checking with previous array-position and swap if
necessary;*/
if (A[j]>A[j+1])
swap(&A[j],&A[j+1]);
else
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]);
}
insertionSort(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