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

Quick Sort Algorithm in C Code

The document contains a C implementation of the QuickSort algorithm, which sorts an array of integers. It includes functions for partitioning the array and swapping elements, as well as a main function that demonstrates sorting a sample array. The output of the program is the sorted array: 5, 7, 8, 9, 10.
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)
27 views2 pages

Quick Sort Algorithm in C Code

The document contains a C implementation of the QuickSort algorithm, which sorts an array of integers. It includes functions for partitioning the array and swapping elements, as well as a main function that demonstrates sorting a sample array. The output of the program is the sorted array: 5, 7, 8, 9, 10.
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

quick sort

#include <stdio.h>

void swap(int* a, int* b);

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

// Choose the pivot


int pivot = arr[high];

// Index of smaller element and indicates


// the right position of pivot found so far
int i = low - 1;

// Traverse arr[low..high] and move all smaller


// elements to the left side. Elements from low to
// i are smaller after every iteration
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}

// Move pivot after smaller elements and


// return its position
swap(&arr[i + 1], &arr[high]);
return i + 1;
}

// The QuickSort function implementation


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

// pi is the partition return index of pivot


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

// recursion calls for smaller elements


// and greater or equals elements
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

void swap(int* a, int* b) {


int t = *a;
*a = *b;
*b = t;
}

int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);

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

return 0;
}
output:
5 7 8 9 10

You might also like