Code for qsort in C with swap
Here is an example of C code for implementing qsort
using a swap function:
#include <stdio.h>
// Swap function
void swap(int a, int b) {
int temp = *a;
a = b;
*b = temp;
}
// Partition function
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);
}
// Quicksort function
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);
}
}
// Main function
int main() {
int arr[] = { 10, 7, 8, 9, 1, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
quickSort(arr, 0, n - 1);
printf("\nSorted array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Explanation:
The code starts with the inclusion of the
stdio.h
header file, which provides input/output functions likeprintf
.The
swap
function takes two integer pointers as arguments and swaps their values using a temporary variable. This function is used to swap the elements during the partitioning process.The
partition
function takes an array,arr
, and two indices,low
andhigh
, as arguments. It selects the last element of the array,arr[high]
, as the pivot and rearranges the other elements such that all elements smaller than the pivot are moved to the left and all elements greater than the pivot are moved to the right. The function returns the index of the pivot element.The
quickSort
function recursively calls itself to sort the array. It takes the array,arr
, and the indiceslow
andhigh
as arguments. It first calls thepartition
function to find the pivot index,pi
, and then recursively callsquickSort
on the subarrays before and after the pivot index.The
main
function initializes an array,arr
, with some values, and calculates the size of the array,n
, using thesizeof
operator.It then prints the original array using a
for
loop and theprintf
function.The
quickSort
function is called with the array,arr
, and the indices0
andn - 1
to sort the array.Finally, the sorted array is printed using another
for
loop and theprintf
function.
The code demonstrates the implementation of the qsort
algorithm using the swap
function for element swapping and the partition
function for partitioning the array. The quickSort
function recursively calls itself to sort the subarrays.