0% found this document useful (0 votes)
13 views5 pages

DSA Lab Assignment 2 Answer

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views5 pages

DSA Lab Assignment 2 Answer

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

DSA Lab Assignment 2

Ques: Following numbers are given for sorting. Write a C program to apply Insertion Sort on them.
64, 34, 25, 12, 22, 11, 90, 5

Ans:

#include <stdio.h>

void insertionSort(int arr[], int n) {

int i, j, temp;

for (i = 1; i < n; i++) {

temp = arr[i];

j = i - 1;

while (j >= 0 && arr[j] > temp) {

arr[j + 1] = arr[j];

j--;

arr[j + 1] = temp;

void printArray(int arr[], int n) {

int i;

for (i = 0; i < n; i++) {

printf("%d ", arr[i]);

printf("\n");

}
int main() {

int arr[] = {64, 34, 25, 12, 22, 11, 90, 5};

int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");

printArray(arr, n);

insertionSort(arr, n);

printf("Sorted array: ");

printArray(arr, n);

return 0;

Output
Ques:

You are working with a large dataset and need to efficiently find the Kth smallest element. How
would you modify the Quick Sort algorithm to find this element without sorting the entire array?

Ans:

#include <stdio.h>

int partition(int arr[], int low, int high) {

int pivot = arr[high];

int i = low - 1;

for (int j = low; j < high; j++) {

if (arr[j] < pivot) {

i++;

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

int temp = arr[i + 1];

arr[i + 1] = arr[high];

arr[high] = temp;

return i + 1;

int quickSelect(int arr[], int low, int high, int k) {

if (low == high) {

return arr[low];

}
int pivotIndex = partition(arr, low, high);

if (k == pivotIndex) {

return arr[k];

} else if (k < pivotIndex) {

return quickSelect(arr, low, pivotIndex - 1, k);

} else {

return quickSelect(arr, pivotIndex + 1, high, k);

int main() {

int arr[] = {12, 3, 5, 7, 4, 19, 26};

int n = sizeof(arr) / sizeof(arr[0]);

int k = 3; // find the 3rd smallest element

int result = quickSelect(arr, 0, n - 1, k - 1);

printf("The %dth smallest element is: %d\n", k, result);

return 0;

Output:

You might also like