Input : 6 3 1 9 4
Output : 1 3 4 6 9
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
int partitionArray(int arr[], int firstIndex, int lastIndex);
void quickSort(int arr[], int firstIndex, int lastIndex);
int main()
{
int a[20], i, n;
printf("Enter the size of Array : ");
scanf("%d", &n);
printf("Enter the array element : \n");
for (i = 0; i < n; i++)
{
printf("Array index[%d] : ", i);
scanf("%d", &a[i]);
}
quickSort(a, 0, n - 1);
for (i = 0; i < n; i++)
{
printf("\t%d", a[i]);
}
getch();
return 0;
}
int partitionArray(int arr[], int firstIndex, int lastIndex)
{
int i, j;
int temp, pivot;
pivot = arr[firstIndex];
i = firstIndex + 1;
j = lastIndex;
do {
while (arr[i] < pivot && i <= lastIndex)
{
i++;
}
while (arr[j] > pivot && j > firstIndex) {
j--;
}
if (i < j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
} while (i < j);
// Swapping of arr[j] and pivot
arr[firstIndex] = arr[j];
arr[j] = pivot;
return j;
}
void quickSort(int arr[], int firstIndex, int lastIndex)
{
int j;
if (firstIndex < lastIndex)
{
j = partitionArray(arr, firstIndex, lastIndex);
quickSort(arr, firstIndex, j - 1);
quickSort(arr, j + 1, lastIndex);
}
}
0 Comments