PROGRAM4-DSA

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

PROGRAM-4

AIM : Write a program for quick sort.


TOOLS USED : Visual Studio Code Editor
SOURCE CODE:
#include <iostream>
using namespace std;
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);
}
}
void display(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << "Array before sorting: ";
display(arr, n);
quickSort(arr, 0, n - 1);
cout << "Array after sorting: ";
display(arr, n);

return 0;
}

OUTPUT:
LEARNING OUTCOMES:
1.Understanding of Quick Sort Algorithm: Gained an understanding of the divide-and-
conquer approach used in Quick Sort, which involves partitioning an array and recursively
sorting the subarrays.
2. Recursive Problem Solving: Developed the ability to apply recursion in sorting algorithms,
breaking down a problem into smaller, manageable subproblems.
3. Time Complexity: Quick Sort is known for its average O(n log n) time complexity,
although in the worst case (e.g., when the array is already sorted), it can degrade to O(n²).

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy