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

Quick Sort

The document contains a C implementation of the Quick Sort algorithm, which sorts an array of integers. It includes functions for swapping elements, partitioning the array, and recursively sorting the left and right halves. The main function demonstrates sorting an example array and printing the sorted result.

Uploaded by

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

Quick Sort

The document contains a C implementation of the Quick Sort algorithm, which sorts an array of integers. It includes functions for swapping elements, partitioning the array, and recursively sorting the left and right halves. The main function demonstrates sorting an example array and printing the sorted result.

Uploaded by

kattasunitha0105
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Quick Sort

#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {

// Initialize pivot to be the first element


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

while (i < j) {

// Find the first element greater than


// the pivot (from starting)
while (arr[i] <= p) {
i++;
}

// Find the first element smaller than


// the pivot (from last)
while (arr[j] > p) {
j--;
}
if (i < j) {
swap(&arr[i], &arr[j]);
}
}
swap(&arr[low], &arr[j]);
return j;
}

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


if (low < high) {

// call partition function to find Partition Index


int pi = partition(arr, low, high);

// Recursively call quickSort() for left and right


// half based on Partition Index
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

int main() {
int arr[] = { 4, 2, 5, 3, 1 };
int n = sizeof(arr) / sizeof(arr[0]);

// calling quickSort() to sort the given array


quickSort(arr, 0, n - 1);

for (int i = 0; i < n; i++)


printf("%d ", arr[i]);

return 0;
}

You might also like