Tuesday, January 31, 2012

Selection sort in c programming

Root function of selection sort:
[sourcecode language="c"]
void Selection_Sort(int A[] , int N)
{
int i , temp , Loc ;

for(i=0 ; i<(N-1) ; i++)
{
Loc = Minimum(A , i , N);
temp = A[i];
A[i] = A[Loc];
A[Loc] = temp;
}
}
[/sourcecode]
Full code of selection sort:

[sourcecode language="c"]
#include <stdio.h>

int Minimum(int [], int, int);
void Selection_Sort(int [], int);
void Print(int [], int);

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

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

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

Selection_Sort(A,n);

Print(A,n);

return 0;
}

int Minimum(int A[] , int i , int N)
{
int j , min , loc ;

min = A[i];
loc = i;
for(j=(i+1) ; j<N ; j++)
{
if(min > A[j])
{
min = A[j];
loc = j;
}
}

return loc;
}

void Selection_Sort(int A[] , int N)
{
int i , temp , Loc ;

for(i=0 ; i<(N-1) ; i++)
{
Loc = Minimum(A , i , N);
temp = A[i];
A[i] = A[Loc];
A[Loc] = temp;
}
}

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

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


[/sourcecode]

1 comment:

  1. I just want to tell you that I'm beginner to weblog and actually liked you're blog site. More than likely I’m likely to bookmark your blog . You definitely have remarkable articles and reviews. Cheers for sharing your web site.

    ReplyDelete

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