In: Computer Science
Please use C language to code all of the problems below. Please submit a .c file for each of the solutions, that includes the required functions, tests you wrote to check your code and a main function to run the code.
Q2. Implement the quick-sort algorithm.
C CODE :
#include<stdio.h>
int partition (int a[], int down, int up)
{
int pivot = a[up]; // pivot element
int i = (down - 1);
for (int j = down; j <= up- 1; j++)
{
if (a[j] < pivot)
{
i++;
int temp =
a[i];
a[i] =
a[j];
a[j] =
temp;
}
}
int temp1 = a[i + 1];
a[i + 1] = a[up];
a[up] = temp1;
return (i + 1);
}
void sort(int a[], int down, int up)
{
if (down < up)
{
int pivot = partition(a, down, up);
// call partition
sort(a, down, pivot - 1); //
recursive function for left hand of array
sort(a, pivot + 1, up); //
recursive function for right hand of array
}
}
int main()
{
int n;
printf("Enter the size of the array : ");
scanf("%d", &n); // read the array size
int a[n];
printf("Enter the array elements : ");
for(int i = 0; i < n; i++)
{
scanf("%d", &a[i]); // read the array
elements
}
sort(a, 0, n - 1); // call the sort function
printf("After sorting the array : ");
for (int i = 0; i < n; i++)
{
printf("%d ", a[i]); // print the
array after sorting
}
return 0;
}
OUTPUT :