C program for Quick Sort.

quick-sort.c

C program to sort the elements of the array in ascending order using Quick Sort technique is as follows:

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

#define SIZE 10
int array_to_sort[SIZE];

void quick_sort(int lower_bound, int upper_bound);
int partition(int left, int right);
void swap(int *num_1, int *num_2);

void main()
{
	int i, j, lower_bound, upper_bound;

	clrscr();

	//Get the elements of Array
	for(i=0; i<SIZE; i++)
	{
		j = i+1;
		printf("\nEnter element %d: ",j);
		scanf("%d", &array_to_sort[i]);
	}

	//Print the unsorted array.
	printf("\n\nUnsorted elements of Array are: ");	
	for(i=0; i<SIZE; i++)
	{
		printf("%d ",array_to_sort[i]);
	}

	//Sort array.
	lower_bound = 0;
	upper_bound = SIZE-1;
	quick_sort(lower_bound, upper_bound);

	//Print the sorted array.
	printf("\n\nSorted elements of Array are: ");	
	for(i=0; i<SIZE; i++)
	{
		printf("%d ",array_to_sort[i]);
	}

	getch();
}

//Logic for Quick Sort.
void quick_sort(int lower_bound, int upper_bound)
{
	int left, right, loc;

	left = lower_bound;
	right = upper_bound;

	if(left < right)
	{
		loc = partition(left, right);
		quick_sort(left, loc-1);
		quick_sort(loc+1, right);
	}
}

int partition(int left, int right)
{
	int loc;

	loc = left;

	while(left < right)
	{
		//Scan from right to left
		while((array_to_sort[loc] <= array_to_sort[right]) && loc < right)
		{
			right = right - 1;
		}
		if(array_to_sort[loc] > array_to_sort[right])
		{
			swap(&array_to_sort[loc], &array_to_sort[right]);
			loc = right;
			left = left + 1;
		}

		//Scan from left to right
		while((array_to_sort[loc] >= array_to_sort[left]) && loc > left)
		{
			left = left + 1;
		}
		if(array_to_sort[loc] < array_to_sort[left])
		{
			swap(&array_to_sort[loc], &array_to_sort[left]);
			loc = left;
			right = right - 1;
		}
	}
	return(loc);
}

void swap(int *num_1, int *num_2)
{
	int temp;
	// printf("Swapping");
	temp = *num_1;
	*num_1 = *num_2;
	*num_2 = temp;
}