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

QuickSort Algorithm in C Programming

The document contains a C program that implements the Quick Sort algorithm to sort an array of integers. It includes functions for swapping elements, partitioning the array, and printing the array. The program prompts the user to enter the number of elements and the elements themselves, then displays the original and sorted arrays.

Uploaded by

stevethheman001
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)
11 views2 pages

QuickSort Algorithm in C Programming

The document contains a C program that implements the Quick Sort algorithm to sort an array of integers. It includes functions for swapping elements, partitioning the array, and printing the array. The program prompts the user to enter the number of elements and the elements themselves, then displays the original and sorted arrays.

Uploaded by

stevethheman001
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

PROGRAM

#include <stdio.h>

// Function to swap elements


void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);

for (int j = low; j <= high - 1; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

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


if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);

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

printf("Original array: \n");


printArray(arr, n);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);

return 0;
}
Output
Enter number of elements: 5
Enter 5 elements: 30
20
50
10
40
Original array:
30 20 50 10 40
Sorted array:
10 20 30 40 50

You might also like