Write a Modular C Programming code for Quick Sort Algorithm DSA
QuickSort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways.
CODE:
#include<stdio.h> 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); } } int main() { int arr[1000]; int n; printf("Enter the size: "); scanf("%d",&n); printf("Enter Numbers: "); for(int i=0;i<n;i++){ arr[i]=rand()%50; 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; }
OUTPUT
Enter the size: 25 Enter Numbers: 41 17 34 0 19 24 28 8 12 14 5 45 31 27 11 41 45 42 27 36 41 4 2 3 42 Sorted array:0 2 3 4 5 8 11 12 14 17 19 24 27 27 28 31 34 36 41 41 41 42 42 45 45 Process returned 0 (0x0) execution time : 1.404 s Press any key to continue.
Please find some more codes of Loops, Condition Statements, 1D Arrays, 2D Arrays, Strings, Pointers, Data Structures, Files, Linked lists, Stacks, Queues, Binary Trees, MISC, Solved model question papers & Hacker Rank all solutions on the below page:
Top 100+ C Programming codes – KLE Technological University