You are on page 1of 2

18/01/2024, 03:53 QuickSort.

DSA LAB\QuickSort.c

1 //Question 1: Write a C program for sorting an array using quick sort.


2 //Code:
3 #include<stdio.h>
4
5 void swap(int *a,int *b){
6 int temp=*a;
7 *a=*b;
8 *b=temp;
9 }
10
11 int partition(int array[], int low, int high) {
12 int pivot = array[low]; // Select the first element as the pivot
13 int i = high + 1; // Index of the smaller element
14
15 for (int j = high; j > low; j--) {
16 // If the current element is greater than the pivot
17 if (array[j] > pivot) {
18 i--; // Decrement index of the smaller element
19 swap(&array[i], &array[j]);
20 }
21 }
22 swap(&array[i - 1], &array[low]);
23 return (i - 1);
24 }
25
26 void quick_sort(int array[],int l,int h){
27 int j;
28 if(l<h){
29 j=partition(array,l,h);
30 quick_sort(array,l,j-1);
31 quick_sort(array,j+1,h);
32 }
33 }
34
35 int main(){
36 int size;
37 printf("Enter the number of elements in the array: ");
38 scanf("%d",&size);
39 int array[size];
40 for(int i=0;i<size;i++)
41 scanf("%d",&array[i]);
42
43 printf("\nUnsorted array: { ");
44 for(int i=0;i<size;i++)
45 printf("%d ",array[i]);
46 printf("}");
47
48 quick_sort(array,0,size-1);
49
50 printf("\nSorted array: { ");
51 for(int i=0;i<size;i++)
52 printf("%d ",array[i]);
53 printf("}");
54
55 return 0;
56 }
57

localhost:51970/f5ddcde2-03a5-4ac4-a65f-dd5094819803/ 1/2
18/01/2024, 03:53 QuickSort.c
58 //Output:
59 /*
60 Enter the number of elements in the array: 8
61 12
62 17
63 52
64 29
65 54
66 72
67 33
68 29
69
70 Unsorted array: { 12 17 52 29 54 72 33 29 }
71 Sorted array: { 12 17 29 29 33 52 54 72 }
72 PS C:\Users\iraki\Desktop\My Program\DSA LAB>
73 */

localhost:51970/f5ddcde2-03a5-4ac4-a65f-dd5094819803/ 2/2

You might also like