23BCE0421
23BCE0421
Name: EK.KAVINKUMAR
Reg. No: 23BCE0421
Code:
#include <stdio.h>
#include <stdlib.h>
if (pi == k)
return arr[pi];
else if (pi < k)
return quickselect(arr, pi + 1, high, k);
else
return quickselect(arr, low, pi - 1, k);
}
return -1;
}
int main() {
int n, k;
int arr[n];
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
Output:
Code:
#include <stdio.h>
int comparisons = 0;
int arr[n];
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
switch(option) {
case 1:
result = linearSearch(arr, n, target, 0);
break;
case 2:
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
result = binarySearch(arr, 0, n - 1, target);
break;
default:
printf("Invalid choice!\n");
return -1;
}
if (result != -1) {
printf("Element found at index: %d\n", result);
} else {
printf("Element not found\n");
}
return 0;
}
Output:
Q3) Greedy Approach :
i) Dijkstra’s Single Source Shortest Path Algorithm
ii) Fractional Knapsack Problem for an airport
permitted baggage scenario.
Code i):
#include <stdio.h>
#include <limits.h>
#define V 9
dist[src] = 0;
int main() {
int graph[V][V] = {
{0, 4, 0, 0, 0, 0, 0, 8, 0},
{4, 0, 8, 0, 0, 0, 0, 0, 0},
{0, 8, 0, 7, 0, 4, 0, 0, 0},
{0, 0, 7, 0, 9, 14, 0, 0, 0},
{0, 0, 0, 9, 0, 10, 0, 0, 0},
{0, 0, 4, 14, 10, 0, 2, 0, 0},
{0, 0, 0, 0, 0, 2, 0, 1, 6},
{8, 0, 0, 0, 0, 0, 1, 0, 7},
{0, 0, 0, 0, 0, 0, 6, 7, 0}
};
int source = 0;
dijkstra(graph, source);
return 0;
}
Output i):
Code ii):
#include <stdio.h>
typedef struct {
int weight;
int value;
float ratio;
} Item;
int main() {
int n, W;
Item items[n];
return 0;
}
Output ii):
typedef struct {
char model[50];
int ram;
} MobilePhone;
int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (L[i].ram <= R[j].ram) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
int main() {
int n;
MobilePhone arr[n];
printf("Enter the details (Model and RAM capacity) of each mobile
phone:\n");
for (int i = 0; i < n; i++) {
printf("Model %d: ", i + 1);
scanf("%s %d", arr[i].model, &arr[i].ram);
}
mergeSort(arr, 0, n - 1);
return 0;
}
Output i) :
Code ii):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int n = (int)log10(x) + 1;
int n2 = n / 2;
int main() {
long long x, y;
printf("Enter two integers: ");
scanf("%lld %lld", &x, &y);
return 0;
}
Output ii):