Advanced DSA_2.1_1723179575685
Advanced DSA_2.1_1723179575685
Quick Sort
Quicksort uses divide-and-conquer, and so it's a recursive
algorithm.
• Finally j position is the PIVOT position so that elements left to PIVOT are
less than PIVOT value and elements right to PIVOT are greater than PIVOT.
If i< j
swap( a[i],a[j])-- swap(16,5)
else
swap(a[j], pivot)
10 5 8 12 15 6 3 9 16 20
10 5 8 12 15 6 3 9 16 20
If i< j
swap( a[i],a[j])----swap 12 &9
else
swap(a[j], pivot)
10 5 8 9 15 6 3 12 16 20
0 1 2 3 4 5 6 7 8 9
10 5 8 9 15 6 3 12 16 20
If i< j
swap( a[i],a[j])- swap 15&3
else
swap(a[j], pivot)
10 5 8 9 3 6 15 12 16 20
10 5 8 9 3 6 15 12 16 20
If i< j
swap( a[i],a[j])
else
swap(a[j], pivot)---- swap 6 &10
6 5 8 9 3 10 15 12 16 20
#include <stdio.h>
void quicksort (int [], int, int);
int main()
{ int list[50];
int size, i;
printf("How many elements u want to Sort :: ");
scanf("%d", &size);
printf("\nEnter the elements below to be sorted :: \n");
for (i = 0; i < size; i++)
{
printf("\nEnter [ %d ] element :: ",i+1);
scanf("%d", &list[i]);
}
quicksort(list, 0, size - 1);
printf("\nAfter implementing Quick sort, Sorted List is :: \n\n");
for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
printf("\n");
return 0;
}
void quicksort(int list[], int low, int high)
{ int pivot, i, j, temp;
if (low < high)
{
pivot = low;
i = low;
j = high;
while (i < j)
{
while (list[i] <= list[pivot] )
{
i++;
}
while (list[j] > list[pivot] )
{
j--;
}
if (i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[j];
list[j] = list[pivot];
list[pivot] = temp;
quicksort(list, low, j - 1);
quicksort(list, j + 1, high);
}