quicksort – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Tue, 29 Sep 2020 08:12:17 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg quicksort – Programmerbay https://programmerbay.com 32 32 C Program to sort an array using Quicksort in Ascending Order https://programmerbay.com/program-to-sort-an-array-using-quicksort/ https://programmerbay.com/program-to-sort-an-array-using-quicksort/#respond Thu, 11 Jun 2020 12:05:22 +0000 https://www.programmerbay.com/?p=2894 Quicksort is based on Divide and Conquer paradigm. It works by partitioning the given input array into two subarrays and sorts them through recursive calls until they get sorted.

In this, a pivot element is used that acts as a base for partitioning the array, where element lesser than pivot element arranged at the left side and bigger ones at the right side.

It requires O(n log n) running time to sort the given array when it comes to the average case.

Therefore, it can be used to sort a large set of elements. However, in the worst case, the running time of this algorithm hops up to O(n2).

Pseudocode

Quicksort( Array,first,last)
IF first <last
partitionpoint = Partition(arr,first,last);
Quicksort(Array,first,partitionpoint-1)
Quicksort(Array,partitionpoint+1,last)

Partitioning

Partition(Array,first,last)
pivot = arr[last]
i=first-1
FOR j=first to last - 1
IF Array[j]<pivot
i=i+1
exchange Array[i] with Array[j]
END IF
END FOR
exchange Array[i] with Array[last]
return i+1

C program to sort an array using Quicksort in Ascending Order

#include<stdio.h>
#define size 5

void quicksort(int arr[],int first,int last)
{

if(first <last)
{
int partitionpoint;
partitionpoint = sort_me(arr,first,last);
quicksort(arr,first,partitionpoint-1);
quicksort(arr,partitionpoint+1,last);
}

}

int sort_me(int arr[],int first,int last)
{
int pivot = arr[last],j,temp,n;
int i=first-1;
for(j=first;j<last;j++)
{
if(arr[j]<pivot)
{
i++;
temp =arr[j];
arr[j]=arr[i];
arr[i]=temp;

}
}
temp =arr[i+1];
arr[i+1]=arr[last];
arr[last]=temp;

return i+1;
}

int main()
{
int arr[size],j,temp,n;
printf("Please enter elements: \n "); 
for(n=0;n<=size-1;n++)
{
scanf("%d",&arr[n]);
}

quicksort(arr,0,size-1);

printf(" \n Sorted Elements :");

for(n=0;n<=size-1;n++)
{
printf("\n %d ",arr[n]);
} 
return 0;

}

 

Output:

quicksort

]]>
https://programmerbay.com/program-to-sort-an-array-using-quicksort/feed/ 0