0% found this document useful (0 votes)
9 views10 pages

AOA Outputs

The document contains multiple experiments demonstrating various algorithms in C programming, including sorting algorithms (Selection Sort and Merge Sort), the Fractional Knapsack problem, Job Sequencing, the Traveling Salesman Problem, Longest Common Subsequence, N-Queens problem, and Graph Coloring. Each experiment includes code snippets, input, and expected output. The experiments illustrate fundamental concepts in algorithm design and implementation.

Uploaded by

purvikajagtap
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)
9 views10 pages

AOA Outputs

The document contains multiple experiments demonstrating various algorithms in C programming, including sorting algorithms (Selection Sort and Merge Sort), the Fractional Knapsack problem, Job Sequencing, the Traveling Salesman Problem, Longest Common Subsequence, N-Queens problem, and Graph Coloring. Each experiment includes code snippets, input, and expected output. The experiments illustrate fundamental concepts in algorithm design and implementation.

Uploaded by

purvikajagtap
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/ 10

Experiment No .

Input :-
// Main function
#include <stdio.h>
int main() {
// Function to perform Selection Sort
int arr[] = {64, 25, 12, 22, 11}; // Example
void selectionSort(int arr[], int n) { array
int i, j, minIndex, temp; int n = sizeof(arr) / sizeof(arr[0]);
// Traverse the array printf("Original array: \n");
for (i = 0; i < n - 1; i++) { printArray(arr, n);
// Assume the first element is the selectionSort(arr, n);
minimum

minIndex = i;
printf("\nSorted array: \n");
// Find the index of the smallest element
in the remaining array printArray(arr, n);

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

if (arr[j] < arr[minIndex]) { return 0;

minIndex = j; }

} Output :-

// Swap the found minimum element with


the first element of unsorted part

temp = arr[minIndex];

arr[minIndex] = arr[i];

arr[i] = temp;

// Function to print the array

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

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

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

printf("\n");

}
Experiment No. 2 int mid = left + (right - left) / 2;

Input:- mergeSort(arr, left, mid);

#include <stdio.h> mergeSort(arr, mid + 1, right);

// Function to merge two subarrays merge(arr, left, mid, right);

void merge(int arr[], int left, int mid, int right) { }}

int n1 = mid - left + 1; // Function to print array

int n2 = right - mid; void printArray(int arr[], int size) {

int L[n1], R[n2]; for (int i = 0; i < size; i++)

for (int i = 0; i < n1; i++) printf("%d ", arr[i]);

L[i] = arr[left + i]; printf("\n");

for (int j = 0; j < n2; j++) }

R[j] = arr[mid + 1 + j]; // Driver code

int i = 0, j = 0, k = left; int main() {

while (i < n1 && j < n2) { int arr[] = {64, 25, 12, 22, 11};

if (L[i] <= R[j]) { int size = sizeof(arr) / sizeof(arr[0]);

arr[k] = L[i]; printf("Unsorted Array:\n");

i++; printArray(arr, size);

} else { mergeSort(arr, 0, size - 1);

arr[k] = R[j]; printf("Sorted Array:\n");

j++; printArray(arr, size);

k++; return 0;

} }

while (i < n1) { Output :-

arr[k] = L[i];

i++;

k++;

while (j < n2) {

arr[k] = R[j];

j++;

k++;

}}

// Function to implement Merge Sort

void mergeSort(int arr[], int left, int right) {

if (left < right) {


Experiment No. 3 maxValue += (double)items[i].value * W
/ items[i].weight;
Input:-
includedItems[index++] = i;
#include <stdio.h>
break;
// Structure to store item properties
}}
struct Item {
printf("Maximum Value = %.2f, Items
int value, weight; Included = [", maxValue);

}; for (int i = 0; i < index; i++) {

void swap(struct Item* a, struct Item* b) { printf("%d", includedItems[i]);

struct Item temp = *a; if (i < index - 1) printf(", ");

*a = *b; }

*b = temp; printf("]\n");

} return maxValue; }

// Function to sort items based on value/weight int main() {


ratio (Descending Order)
struct Item items1[] = {{60, 10}, {100, 20},
void sortItems(struct Item items[], int n) { {120, 30}};

for (int i = 0; i < n - 1; i++) { int W1 = 50;

for (int j = 0; j < n - i - 1; j++) { int n1 = sizeof(items1) / sizeof(items1[0]);

double ratio1 = (double)items[j].value / printf("Test Case 1:\n");


items[j].weight;
fractionalKnapsack(W1, items1, n1);
double ratio2 = (double)items[j +
1].value / items[j + 1].weight; struct Item items2[] = {{10, 1}, {20, 1}, {30,
1}};
if (ratio1 < ratio2) {
int W2 = 2;
swap(&items[j], &items[j + 1]);
int n2 = sizeof(items2) / sizeof(items2[0]);
}}}}
printf("\nTest Case 2:\n");
double fractionalKnapsack(int W, struct Item
items[], int n) { fractionalKnapsack(W2, items2, n2);

sortItems(items, n); return 0;

double maxValue = 0.0; }

int includedItems[n], index = 0; Output :-

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

if (W >= items[i].weight) {

W -= items[i].weight;

maxValue += items[i].value;

includedItems[index++] = i;

} else {
Experiment No. 4 totalProfit += jobs[i].profit;

Input:- selectedJobs[jobCount++] = jobs[i].id;

#include <stdio.h> break;

#include <stdlib.h> }}}

struct Job { printf("Scheduled Jobs: [");

int id, deadline, profit; for (int i = 0; i < jobCount; i++) {

}; printf("%d", selectedJobs[i]);

int compare(const void* a, const void* b) { if (i < jobCount - 1) printf(", "); }

return ((struct Job*)b)->profit - ((struct printf("]\nTotal Profit: %d\n", totalProfit); }


Job*)a)->profit;
int main() {
}
struct Job jobs1[] = {{1, 2, 100}, {2, 1, 19}, {3,
int findMaxDeadline(struct Job jobs[], int n) { 2, 27}, {4, 1, 25}, {5, 3, 15}};

int max = 0; int n1 = sizeof(jobs1) / sizeof(jobs1[0]);

for (int i = 0; i < n; i++) printf("Test Case 1:\n");

if (jobs[i].deadline > max) jobSequencing(jobs1, n1);

max = jobs[i].deadline; struct Job jobs2[] = {{1, 1, 50}, {2, 1, 40}, {3,
1, 30}};
return max;
int n2 = sizeof(jobs2) / sizeof(jobs2[0]);
}
printf("\nTest Case 2:\n");
void jobSequencing(struct Job jobs[], int n) {
jobSequencing(jobs2, n2);
qsort(jobs, n, sizeof(struct Job), compare); //
Sort jobs by profit return 0;

int maxDeadline = findMaxDeadline(jobs, n); }

int slot[maxDeadline]; // Array to keep track Output :-


of occupied slots

for (int i = 0; i < maxDeadline; i++)

slot[i] = -1; // Initialize all slots as empty

int totalProfit = 0;

int selectedJobs[n], jobCount = 0;

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

for (int j = jobs[i].deadline - 1; j >= 0; j--) {

if (slot[j] == -1) {

slot[j] = jobs[i].id;
Experiment No. 5 void inputCostMatrix() {

Input :- printf("Enter the number of cities: ");

#include <stdio.h> scanf("%d", &n);

#include <limits.h> printf("Enter the cost matrix (enter 0 for same


city):\n");
#define MAX 10 // Maximum number of cities
for (int i = 0; i < n; i++) {
#define INF INT_MAX
for (int j = 0; j < n; j++) {
int cost[MAX][MAX]; // Cost matrix
scanf("%d", &cost[i][j]);
int memo[MAX][1 << MAX]; // Memoization
table }}}

int n; int main() {

int tsp(int pos, int mask) { inputCostMatrix();

if (mask == (1 << n) - 1) // If all cities are initializeMemo();


visited
printf("\nMinimum Cost of Tour: %d\n", tsp(0,
return cost[pos][0]; // Return cost to return 1));
to starting city
return 0;
if (memo[pos][mask] != -1)
}
return memo[pos][mask];

int minCost = INF;

for (int city = 0; city < n; city++) {

if ((mask & (1 << city)) == 0) { // If city is


not visited

int newCost = cost[pos][city] + tsp(city,


mask | (1 << city));

if (newCost < minCost)

minCost = newCost;

return memo[pos][mask] = minCost;

void initializeMemo() {

for (int i = 0; i < MAX; i++)

for (int j = 0; j < (1 << MAX); j++)

memo[i][j] = -1;

}
Experiment No. 6

Input :- else

#include <stdio.h> j--;

#include <string.h> }

void findLCS(char *X, char *Y) { printf("String 1: %s\n", X);

int m = strlen(X); printf("String 2: %s\n", Y);

int n = strlen(Y); printf("Length of Longest Common


Subsequence: %d\n", L[m][n]);
int L[m + 1][n + 1];
printf("Longest Common Subsequence:
for (int i = 0; i <= m; i++) { %s\n", lcs);

for (int j = 0; j <= n; j++) { }

if (i == 0 || j == 0) int main() {

L[i][j] = 0; char X[100], Y[100];

else if (X[i - 1] == Y[j - 1]) printf("Enter String 1: ");

L[i][j] = L[i - 1][j - 1] + 1; scanf("%s", X);

else printf("Enter String 2: ");

L[i][j] = (L[i - 1][j] > L[i][j - 1]) ? L[i - 1][j] scanf("%s", Y);
: L[i][j - 1];
// Find and print LCS
}
findLCS(X, Y);
}
return 0;
int index = L[m][n];
}
char lcs[index + 1];
Output :-
lcs[index] = '\0';

int i = m, j = n;

while (i > 0 && j > 0) {

if (X[i - 1] == Y[j - 1]) {

lcs[index - 1] = X[i - 1];

i--;

j--;

index--;

else if (L[i - 1][j] > L[i][j - 1])

i--;
Experiment No. 7 for (int i = 0; i < N; i++) { // Try placing a
queen in each row
Input :-
if (isSafe(i, col)) {
#include <stdio.h>
board[i][col] = 1; // Place queen
#include <stdbool.h>
res = solveNQueens(col + 1) || res; //
#define MAX 10 Try next column

int board[MAX][MAX]; board[i][col] = 0; // Backtrack if needed

void printSolution() { }}

for (int i = 0; i < N; i++) { return res; }

for (int j = 0; j < N; j++) void solve() {

printf(board[i][j] ? "Q " : ". "); printf("Enter the value of N: ");

printf("\n"); scanf("%d", &N);

} printf("\n"); } for (int i = 0; i < N; i++)

// Function to check if it's safe to place a queen for (int j = 0; j < N; j++)
at board[row][col]
board[i][j] = 0;
bool isSafe(int row, int col) {
if (!solveNQueens(0))
int i, j;
printf("No solution exists\n");
for (i = 0; i < col; i++)
}
if (board[row][i])
int main() {
return false;
solve();
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
return 0; }
if (board[i][j])
Output :-
return false;

for (i = row, j = col; i < N && j >= 0; i++, j--)

if (board[i][j])

return false;

return true; }

bool solveNQueens(int col) {

if (col >= N) {

printSolution(); // Print one valid solution

return true; // Continue to find more


solutions

bool res = false;


Experiment No. 8 :- void graphColoring() {

Input:- printf("Enter number of vertices: ");

#include <stdio.h> scanf("%d", &V);

#include <stdbool.h> printf("Enter the adjacency matrix:\n");

#define MAX 10 for (int i = 0; i < V; i++)

int V, m; // Number of vertices and colors for (int j = 0; j < V; j++)

int graph[MAX][MAX]; // Adjacency matrix of scanf("%d", &graph[i][j]);


the graph
printf("Enter the number of colors: ");
int color[MAX]; // Color array for vertices
scanf("%d", &m);
bool isSafe(int v, int c) {
for (int i = 0; i < V; i++) // Initialize color array
for (int i = 0; i < V; i++) to 0

if (graph[v][i] && color[i] == c) // If adjacent color[i] = 0;


vertex has same color
if (!graphColoringUtil(0))
return false;
printf("No solution exists\n"); }
return true; }
int main() {
bool graphColoringUtil(int v) {
graphColoring();
if (v == V) { // All vertices are assigned a
color return 0;

for (int i = 0; i < V; i++) }

printf("Vertex %d -> Color %d\n", i,


color[i]);

printf("\n");

return true; // Found a valid coloring

bool res = false; // Flag to check if a solution


is found

for (int c = 1; c <= m; c++) { // Try different


colors

if (isSafe(v, c)) {

color[v] = c; // Assign color c to vertex v

res = graphColoringUtil(v + 1) || res; //


Recur for next vertex

color[v] = 0; // Backtrack

return res; }
Experiment No. 9

#include <stdio.h> printf("Enter the pattern: ");

#include <string.h> gets(pattern);

// Function to perform Naive Pattern Searching naivePatternSearch(text, pattern);

void naivePatternSearch(char text[], char


pattern[]) {
return 0;
int n = strlen(text);
}
int m = strlen(pattern);

Output :-
printf("Occurrences of pattern:\n");

for (int i = 0; i <= n - m; i++) { // Loop through


the text

int j;

// Check for pattern match at current


position

for (j = 0; j < m; j++) {

if (text[i + j] != pattern[j]) {

break; // Mismatch found, stop


checking further

if (j == m) { // If the pattern is found

printf("Pattern found at index %d\n", i);

// Driver function

int main() {

char text[100], pattern[50];

// Input text and pattern from user

printf("Enter the text: ");

gets(text);
Experiment No. 10 int q = 101;
search(pat, txt, q);
#include <stdio.h> return 0;
#include <string.h> }
#define d 256
// Rabin-Karp Algorithm
void search(char pat[], char txt[], int q) {
int M = strlen(pat); // Length of pattern
int N = strlen(txt); // Length of text
int i, j;
int p = 0; // Hash value for pattern
int t = 0; // Hash value for text window
int h = 1;

// Compute h = (d^(M-1)) % q
for (i = 0; i < M - 1; i++)
h = (h * d) % q;

// Compute initial hash values for pattern and


first window of text
for (i = 0; i < M; i++) {
p = (d * p + pat[i]) % q;
t = (d * t + txt[i]) % q;
}
for (i = 0; i <= N - M; i++) {
// Check hash values
if (p == t) {
// If hash matches, check character by
character
for (j = 0; j < M; j++) {
if (txt[i + j] != pat[j])
break;
}
if (j == M)
printf("Pattern found at index %d\n",
i);
}
if (i < N - M) {
t = (d * (t - txt[i] * h) + txt[i + M]) % q;

// Ensure non-negative hash


if (t < 0)
t = (t + q);
}
}
}

// Driver Code
int main() {
char txt[] = "PROGRAMMERS PROGRAM
WELL";
char pat[] = "PROG";

You might also like