Skip to main content

Quick Sort in C

#include<stdio.h>
#include<conio.h>

int comp=0,s=0;
int quick(int array[],int n,int beg,int end,int loc)
	{
	int left=beg,right=end,temp;
	loc=beg;
	right_to_left:
	while(array[loc]<=array[right] && loc!=right)
		{
		right=right-1;
		comp++;
		}
	if(loc==right)
		return(loc);
	if(array[loc]>array[right])
		{
		s++;
		temp=array[loc];
		array[loc]=array[right];
		array[right]=temp;
		loc=right;
		goto left_to_right;
		}
	left_to_right:
	while(array[left]<=array[loc] && left!=loc)
		{
		left=left+1;
		comp++;
		}
	if(loc==left)
		return (loc);
	if(array[left]>array[loc])
		{
		s++;
		temp=array[loc];
		array[loc]=array[left];
		array[left]=temp;
		loc=left;
		goto right_to_left;
		}
	}
void main()
	{
	int array[30],n,i,top=0,lower[10],upper[10];
	int beg,end,loc;
	printf("HOW MANY ELEMENTYOU WANT: ");
	scanf("%d",&n);
	for(i=1;i<=n;i++)
		{
		printf("array[%d]",i);
		scanf("%d",&array[i]);
		}
	if(n>1)
		{
		top=top+1;
		lower[1]=1;
		upper[1]=n;
		}
	while(top!=0)
		{
		beg=lower[top];
		end=upper[top];
		top=top-1;
		loc=quick(array,n,beg,end,loc);
		if(beg<loc-1)
			{
			top=top+1;
			lower[top]=beg;
			upper[top]=loc-1;
			}
		if(loc+1<end)
			{
			top=top+1;
			lower[top]=loc+1;
			upper[top]=end;
			}
		}
	printf("\nAFTER SORTING");
	for(i=1;i<=n;i++)
		{
		printf("\nARRAY[%d]=%d",i,array[i]);
		}
	getch();
	}


Spread the love

Mashkawat Ahsan

I am Mashkawat Ahsan. Wikipedian, Mozillian, tech activist, art lover. Thank you for visiting.

Leave a Reply

Your email address will not be published. Required fields are marked *