C program for a given sorting technique

Posted: January 30, 2012 in Lab 4

Problem Statement- A sorting technique employs selection of the minimum, putting it in the front position of the list and, simultaneous selection of the maximum, putting it at the end position. Write a program for it, using only one array.

#include<stdio.h>
#include<stdlib.h>
int swap(int* , int*);
int swap(int *a, int *b)
{
	int temp;
	temp=*a;
	*a=*b;
	*b=temp;
return 0;
}
int main()
{
	int *arr,n,i,j,min,max=0,pos_max,pos_min,f=0;
	printf("Enter no. of terms\n");
	scanf("%d",&n);
	arr=(int*)malloc(n*sizeof(int));
	printf("Enter elements\n");
	for(i=0;i<n;i++)
		scanf("%d",(arr+i));
		for(i=0;i<(n/2);i++)
	{
		max=0;
		min=*(arr+i);
			for(j=i;j<(n-i);j++)
		{
				if(*(arr+j)>max)
			{
				max=*(arr+j);
					pos_max=j;
				continue;
			}
				if(*(arr+j)<min)
			{
				min=*(arr+j);
				pos_min=j;
				f=1;
				continue;
			}
		}
		if(f==0)
			pos_min=i;
		if(pos_min==i&&pos_max==(n-1-i))
			continue;
		if(pos_max==i&&pos_min==(n-1-i))
		{
			swap((arr+(n-1-i)),(arr+i));
		}
		else
		{
			swap((arr+(n-1-i)),(arr+(pos_max)));
			swap((arr+(i)),(arr+(pos_min)));
		}
		
	}
	printf("Sorted array is\n");
      for(i=0;i<n;i++)
		printf("%d\n",*(arr+i));
return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s