This 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 recursively sorting the partitions. The program prompts the user for the number of elements and the elements themselves, then outputs the sorted array.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
13 views2 pages
Quick Sort
This 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 recursively sorting the partitions. The program prompts the user for the number of elements and the elements themselves, then outputs the sorted array.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2
#include <stdio.
h>
// Function to swap two elements
void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; }
// Partition function to find the partitioning index
int partition(int arr[], int low, int high) { int pivot = arr[high]; // Choosing the last element as pivot int i = low - 1; // Index of smaller element
for (int j = low; j <= high - 1; j++) {
// If current element is smaller than or equal to pivot if (arr[j] <= pivot) { i++; // Increment the index of smaller element swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); }
// Quick Sort function
void quickSort(int arr[], int low, int high) { if (low < high) { // Partition the array and get the pivot index int pi = partition(arr, low, high);
// Recursively sort elements before and after partition
quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } }
int main() { int n;
// Input: Number of elements
printf("Enter the number of elements: "); scanf("%d", &n);
int arr[n];
// Input: Elements of the array
printf("Enter the elements: \n"); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); }
// Perform Quick Sort
quickSort(arr, 0, n - 1);
// Output: Sorted array
printf("Sorted array: \n"); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n");