You are on page 1of 7

OUTCOME

BASED LAB
TASK
REPORT
DATA STRUCTURES AND ALGORITHMS
FIND THE Kth SMALLEST ELEMENT IN THE ARRAY
OUTCOME BASED LAB TASK REPORT

Submitted by
HARIHARAN M
7376211SE118

BANNARI AMMAN INSTITUTE OF TECHNOLOGY


(An Autonomous Institution Affiliated to Anna University,
Chennai) SATHYAMANGALAM-638401

OCTOBER 2022
1. Objective of the experiment:
To find the Kth smallest element in the given array.

2. Introduction:
An array is defined as the collection of similar type of data
items stored at contiguous memory locations. Arrays are the derived
data type in C programming language which can store the primitive
type of data such as int, char, double, float, etc. Task is to find the Kth
smallest element in the given array. It is given that all array elements
are distinct.

3. Block Diagram:

4. Proposed methodology:
Run quick sort algorithm on the input array
i) In this algorithm pick a pivot element and move it to
its correct position.
ii) Now, if index of pivot is equal to K then return the
value, else if the index of pivot is greater than K, then
recur for the left subarray, else recur for the right
subarray
iii) Repeat this process until the element at index K is not
found

5. Implementation of code for above methodology:

#include <stdio.h>
int partition(int arr[], int l, int r);
int kthSmallest(int arr[], int l, int r, int K)
{
if (K > 0 && K <= r - l + 1) {
int pos = partition(arr, l, r);
if (pos - l == K - 1)
return arr[pos];
if (pos - l > K - 1)
return kthSmallest(arr, l, pos - 1, K);
return kthSmallest(arr, pos + 1, r, K - pos + l - 1);
}
}
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int l, int r)
{
int x = arr[r], i = l;
for (int j = l; j <= r - 1; j++) {
if (arr[j] <= x) {
swap(&arr[i], &arr[j]);
i++;
}
}
swap(&arr[i], &arr[r]);
return i;
}
int main()
{
int size;
printf("Enter the Size of Array: ");
scanf("%d",&size);
int arr[size];
printf("Enter the array elements: ");
for(int i = 0; i < size; ++i) {
scanf("%d", &arr[i]);
}
int N = sizeof(arr) / sizeof(arr[0]), K;
printf("Enter The K value:");
scanf("%d",&K);
printf("K'th smallest element is %d", kthSmallest(arr, 0, N - 1, K));
return 0;
}
6.Output:
7.Conclusion:
Successfully found the Kth smallest element in the given array.

8. References:
● afteracademy.com
● www.geeksforgeeks.org
● Lecture material.

You might also like