0% found this document useful (0 votes)
10 views2 pages

Quick Sort Code for Beginners

The document describes the quick sort algorithm. It includes the code to implement quick sort in C by partitioning the array around a pivot element and recursively sorting the subarrays. The code takes an array as input, applies the quick sort algorithm, and outputs the sorted array along with the time taken.

Uploaded by

krkishangowda50
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views2 pages

Quick Sort Code for Beginners

The document describes the quick sort algorithm. It includes the code to implement quick sort in C by partitioning the array around a pivot element and recursively sorting the subarrays. The code takes an array as input, applies the quick sort algorithm, and outputs the sorted array along with the time taken.

Uploaded by

krkishangowda50
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Quick Sort

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

int partition(int arr[], int low, int high) {


int pivot = arr[low];
int i = low;
int j = high;

while (i < j) {
while (arr[i] <= pivot && i <= high - 1) {
i++;
}

while (arr[j] > pivot && j >= low + 1) {


j--;
}
if (i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[low];
arr[low] = arr[j];
arr[j] = temp;
return j;
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pIndex = partition(arr, low, high);
quickSort(arr, low, pIndex - 1);
quickSort(arr, pIndex + 1, high);
}
}

int main() {
int n, arr[10];
clock_t start, end;
double time_taken;

start = clock();
printf("Array Size: ");
scanf("%d", &n);

printf("Array Elements: \n");


for(int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

printf("Before Sorting Array: \n");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

quickSort(arr, 0, n - 1);

printf("After Sorting Array: \n");


for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

end = clock();
time_taken = (double) (end-start) / CLOCKS_PER_SEC;
printf("Time Taken: %f seconds", time_taken);
getch();

return 0;
}

You might also like