0% found this document useful (0 votes)
2 views

quick4

This document contains a C program that implements the Quick Sort algorithm. It includes functions for swapping elements, partitioning the array, and recursively sorting the array. The program demonstrates sorting an example array and prints the original and sorted arrays.

Uploaded by

adityamg22hcompe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

quick4

This document contains a C program that implements the Quick Sort algorithm. It includes functions for swapping elements, partitioning the array, and recursively sorting the array. The program demonstrates sorting an example array and prints the original and sorted arrays.

Uploaded by

adityamg22hcompe
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

EXPERIMENT NO.

//quick sort

#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}

int partition(int a[], int lb, int ub) {


int pivot = a[lb];
int up = ub;
int down = lb;

printf("\nPartitioning with pivot = %d\n", pivot);


printf("Array before partitioning: ");
for (int i = lb; i <= ub; i++) {
printf("%d ", a[i]);
}
printf("\n");

while (down < up) {


while (a[down] <= pivot && down < up) {
down++;
}
while (a[up] > pivot) {
up--;
}

if (down < up) {


swap(&a[down], &a[up]);
printf("Swapped: ");
for (int i = lb; i <= ub; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
1
}

swap(&a[lb], &a[up]);
printf("Swapped pivot: ");
for (int i = lb; i <= ub; i++) {
printf("%d ", a[i]);
}
printf("\n");

return up;
}

void QuickSortMethod(int a[], int lb, int ub) {


if (lb >= ub) {
return;
}

int j = partition(a, lb, ub);


QuickSortMethod(a, lb, j - 1);
QuickSortMethod(a, j + 1, ub);
}

void printArray(int a[], int size) {


for (int i = 0; i < size; i++) {
printf("%d ", a[i]);
}
printf("\n");
}\

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

printf("Original Array: ");


printArray(arr, n);

QuickSortMethod(arr, 0, n - 1);

printf("\nSorted Array: ");


printArray(arr, n);

2
return 0;
}

You might also like