Thursday, January 26, 2012

Insertion sort in programming

Function of Insartion sort:
[sourcecode language="c"]
void Insertion_Sort(int A[] , int N)
{
int i , j , temp ;

for(i=2 ; i<N ; i++)
{
temp = A[i];
j = i-1;
while(temp < A[j])
{
A[j+1] = A[j];
j--;
}
A[j+1] = temp;
}
}

[/sourcecode]

Main code of program:
[sourcecode language="c"]
#include <stdio.h>

void Insertion_Sort(int [], int);
void Print(int [], int);

int main()
{
int i , n ;
int A[50];

A[0] = -32768;

printf("How many Elements (Not more than 50 !!): ");
scanf("%d",&n);

printf("Enter %d Numbers: \n",n);
for(i=1 ; i<(n+1) ; i++)
{
scanf("%d",&A[i]);
}

Insertion_Sort(A,n+1);

Print(A,n+1);

return 0;
}

void Insertion_Sort(int A[] , int N)
{
int i , j , temp ;

for(i=2 ; i<N ; i++)
{
temp = A[i];
j = i-1;
while(temp < A[j])
{
A[j+1] = A[j];
j--;
}
A[j+1] = temp;
}
}

void Print(int A[] , int N)
{
int i;

printf("After Sorting The Elements Are: \n");
for(i=1 ; i<N ; i++)
{
printf("%4d",A[i]);
}
printf("\n");
}

[/sourcecode]

2 comments:

  1. I just want to mention I am beginner to blogging and site-building and actually savored you're website. Very likely I’m going to bookmark your blog . You absolutely come with good stories. Thanks a bunch for sharing with us your web site.

    ReplyDelete
  2. I just want to mention I am very new to weblog and honestly enjoyed your web site. Very likely I’m likely to bookmark your site . You absolutely have outstanding posts. Kudos for revealing your website page.

    ReplyDelete

Note: Only a member of this blog may post a comment.