0% found this document useful (0 votes)
79 views24 pages

MY Pavithra Documents PDF

Uploaded by

Dhanush Arjunan
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)
79 views24 pages

MY Pavithra Documents PDF

Uploaded by

Dhanush Arjunan
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/ 24

1. Sort the following array of numbers 10,56,33,78,21,45,15,100 using Bubble sort technique?

#include <stdio.h>

void swap(int *xp, int *yp) {

int temp = *xp;

*xp = *yp;

*yp = temp;

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

int i, j;

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

// Last i elements are already in place

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

if (arr[j] > arr[j + 1]) {

swap(&arr[j], &arr[j + 1]);

// Function to print the array

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

int i;

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

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

printf("\n");

}
int main() {

int arr[] = {10, 56, 33, 78, 21, 45, 15, 100};

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

printf("Unsorted array is \n");

printArray(arr, n);

bubbleSort(arr, n);

printf("Sorted array is \n");

printArray(arr, n);

return 0;

2. 12. Write a C program to implement Bubble sort?

#include <stdio.h>

void swap(int *xp, int *yp) {

int temp = *xp;

*xp = *yp;

*yp = temp;

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

int i, j;

// Optimization: Use a flag to track if swaps occurred

int swapped;

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

swapped = 0; // Initialize flag for each pass


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

if (arr[j] > arr[j + 1]) {

swap(&arr[j], &arr[j + 1]);

swapped = 1; // Set flag if a swap occurred

// If no swaps occurred in the inner loop, the array is already sorted

if (swapped == 0) {

break;

// Function to print the array

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};

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

printf("Unsorted array is \n");

printArray(arr, n);

bubbleSort(arr, n);
printf("Sorted array is \n");

printArray(arr, n);

return 0;

3. Write an algorithm to insert an element at a specific position in an array?

#include <stdio.h>

void insertElement(int arr[], int n, int x, int pos) {


// Check for invalid positions
if (pos < 0 || pos > n) {
printf("Invalid position\n");
return;
}

// Check if array is full


if (n == sizeof(arr) / sizeof(arr[0])) {
printf("Array is full\n");
return;
}

// Shift elements one position forward from the insertion position


for (int i = n - 1; i >= pos; i--) {
arr[i + 1] = arr[i];
}

// Insert the new element at the desired position


arr[pos] = x;

// Update the array size (optional)


n++; // Only if you need to keep track of the number of elements after insertion
}

int main() {
int arr[100] = {1, 5, 8, 12};
int n = sizeof(arr) / sizeof(arr[0]); // Get the number of elements (optional)

int x = 10; // Element to insert


int pos = 2; // Position to insert at

insertElement(arr, n, x, pos);
printf("Array after insertion: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

4. Write an algorithm to delete an element from a given position in an array?

#include <stdio.h>

void deleteElement(int arr[], int n, int pos) {

if (pos < 0 || pos >= n) {

printf("Invalid position!\n");

return;

// Shift elements to the left to overwrite the deleted element

for (int i = pos; i < n - 1; i++) {

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

// Decrement the array size (optional, if you want to keep track of the actual number of elements)

n--;

printf("Array after deletion:\n");

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

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

printf("\n");

}
int main() {

int arr[] = {10, 20, 30, 40, 50};

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

int pos;

printf("Enter the position of the element to delete (0 to %d): ", n - 1);

scanf("%d", &pos);

deleteElement(arr, n, pos);

return 0;

5. What is algorithm analysis? Explain steps involved in Algorithm analysis?

Algorithm analysis is all about understanding how well an algorithm performs. It's like figuring out
how fast and efficient a recipe is for cooking a meal. Here are the key steps involved:

Meaning:

We want to know how much time and memory an algorithm needs to solve a problem.

This helps us choose the best algorithm for a specific task, especially when dealing with large
amounts of data.

Steps:

Define the Problem:

What kind of data does the algorithm work with?

How big is the typical input (number of elements)?

Choose Metrics:
Time Complexity: How long does the algorithm take to run? (e.g., O(n), O(n^2))

Lower is usually better for speed.

Space Complexity: How much memory does the algorithm use? (also in Big O notation)

Lower is better for memory usage.

Analyze the Algorithm:

Break down the steps and see how many times each step runs based on the input size.

Identify the key parts that use the most time and memory.

Interpret the Results:

Understand how the algorithm performs based on the problem and typical data sizes.

Consider trade-offs between time and space if needed.

Compare different algorithms for the same problem and choose the most efficient one overall.

6. Explain the two major measures of efficiency of algorithms?

The two main ways to measure an algorithm's efficiency are:

Time Complexity: How long it takes the algorithm to run, based on the size of the input data.
Imagine how many steps it needs to complete the task.

Space Complexity: How much memory the algorithm uses, also based on the input data size.
Think of how much extra space it needs to borrow to work on the problem.

7. What is the time space tradeoff? Give any two examples?

The time-space tradeoff is a fundamental concept in computer science where you can
improve the speed (time) of a program by using more memory (space), or vice-versa. There's a
constant balancing act between these two factors.

Here are two examples of time-space tradeoffs:


Compressed vs. Uncompressed Data: Storing data in its uncompressed form takes up
more space but allows for much faster access. Compressed data takes less space, but requires time
to decompress before you can use it. If you frequently access the data, keeping it uncompressed
might be better, but if storage space is limited, compressing it makes sense even if it takes a little
longer to access.

Lookup Tables vs. Calculations: A lookup table is a giant table that stores pre-computed
answers. This can significantly speed up calculations because you just look up the answer instead of
recomputing it every time. However, lookup tables take up a lot of space. If the calculation is simple
and storage space is limited, it might be faster to just do the calculation on the fly, even if it takes a
bit longer.

8. How is a multi dimensional array declared and initialized? Give examples?

Declaring a Multidimensional Array:

data_type array_name[size1][size2]...[sizeN];

Declaring a 2D Array (Integer Matrix)

int matrix[3][4];

9. Write a C program to read and print elements in a 3 dimensional array.?

#include <stdio.h>

int main() {
int dim1, dim2, dim3;

// Get dimensions from the user


printf("Enter the dimensions of the 3D array (rows columns layers): ");
scanf("%d %d %d", &dim1, &dim2, &dim3);

int arr[dim1][dim2][dim3];

// Read elements from the user


printf("Enter the elements of the array:\n");
for (int i = 0; i < dim1; i++) {
for (int j = 0; j < dim2; j++) {
for (int k = 0; k < dim3; k++) {
printf("Enter element at [%d][%d][%d]: ", i, j, k);
scanf("%d", &arr[i][j][k]);
}
}
}

// Print the elements


printf("\nThe elements of the array are:\n");
for (int i = 0; i < dim1; i++) {
for (int j = 0; j < dim2; j++) {
for (int k = 0; k < dim3; k++) {
printf("%d ", arr[i][j][k]);
}
printf("\n");
}
printf("\n"); // Add a newline for separation between layers
}

return 0;
}

10. How is a sparse matrix represented in memory? Give one example.?

Regular matrices store all elements in a 2D array, wasting space for zeros in sparse matrices.
Sparse matrices use specialized representations to store only non-zero elements.

One common way is Compressed Sparse Row (CSR). It uses three arrays:

1. Values: Stores the non-zero values.


2. Column Indices: Stores the column index for each non-zero value.
3. Row Pointers: Stores the starting index of non-zero elements in the 'Values' array for
each row.

For example, a sparse matrix with zeros at (1,2) and (2,1) can be represented as:

Values: [3, 5] (non-zero values) Column Indices: [1, 0] (corresponding columns) Row
Pointers: [0, 1, 2] (start of non-zeros in each row)

This saves space and allows faster computations on non-zero elements.


11. Write a C program to represent a 2d sparse matrix of size m x n to array representation with
row,column and value.?

#include <stdio.h>

#define MAX_SIZE 100

int main() {

int m, n, non_zero_elements = 0;

printf("Enter the size of the matrix (m x n): ");

scanf("%d %d", &m, &n);

// Original sparse matrix (example)

int sparse_matrix[MAX_SIZE][MAX_SIZE] = {

{0, 7, 0, 0},

{0, 0, 3, 0},

{5, 0, 0, 1},

};

// Count non-zero elements

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

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

if (sparse_matrix[i][j] != 0) {

non_zero_elements++;

// Array to store row, column, and value (sparse representation)


int sparse_array[3][non_zero_elements];

int k = 0;

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

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

if (sparse_matrix[i][j] != 0) {

sparse_array[0][k] = i; // Row index

sparse_array[1][k] = j; // Column index

sparse_array[2][k] = sparse_matrix[i][j]; // Value

k++;

printf("\nSparse representation (row, column, value):\n");

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

printf("%d %d %d\n", sparse_array[0][i], sparse_array[1][i], sparse_array[2][i]);

return 0;

12. Write a short note on memory management functions in C with an example for each.?

## Memory Management Functions in C

C provides several functions for allocating and deallocating memory during program execution. These
functions are crucial for dynamic memory management, allowing you to work with data structures
whose size is not known beforehand. All these functions are declared in the `<stdlib.h>` header file.

Here's a breakdown of the key functions:


1. **malloc()**

- allocates a block of memory of a specified size in bytes.

- returns a `void*` pointer, which needs to be cast to the desired data type.

- **doesn't initialize** the allocated memory.

**Example:**

```c

int* ptr = (int*)malloc(sizeof(int) * 10); // Allocate memory for 10 integers

if (ptr == NULL) {

// handle allocation failure

// Use the allocated memory (e.g., ptr[0] = 10)

free(ptr); // Release the memory when done

```

2. **calloc()**

- allocates memory for a specified number of elements of a given size.

- initializes the allocated memory to zero.

- returns a `void*` pointer, similar to `malloc()`.

**Example:**

```c

char* buffer = (char*)calloc(100, sizeof(char)); // Allocate 100 bytes and initialize to zeros

if (buffer == NULL) {
// handle allocation failure

// Use the buffer (e.g., strcpy(buffer, "Hello"))

free(buffer); // Release the memory when done

```

3. **realloc()**

- resizes an existing memory block allocated with `malloc()` or `calloc()`.

- can increase or decrease the size of the block.

- returns a `void*` pointer to the resized block (may change the original pointer).

**Example:**

```c

int* data = (int*)malloc(sizeof(int) * 5);

if (data == NULL) {

// handle allocation failure

// Use the memory

int* new_data = (int*)realloc(data, sizeof(int) * 10); // Increase size to hold 10 integers

if (new_data == NULL) {

// handle reallocation failure (original memory may still be allocated)

// Use the resized memory


free(new_data); // Release the resized memory

```

4. **free()**

- releases a block of memory previously allocated using `malloc()`, `calloc()`, or `realloc()`.

- takes a `void*` pointer to the memory block to be freed.

**Example (refer to previous examples for allocation):**

```c

free(ptr); // Release memory allocated with malloc()

free(buffer); // Release memory allocated with calloc()

free(new_data); // Release memory after realloc()

```

**Important Note:**

- Always check the return value of allocation functions (e.g., `malloc()`) for errors (NULL pointer).

- Ensure you free all dynamically allocated memory before the program exits to avoid memory leaks.

13. Write an Algorithm to count the number of nodes in a singly linked list?

#include <stdio.h>

#include <stdlib.h>

struct Node {

int data;

struct Node* next;

};

// Function to create a new node


struct Node* newNode(int data) {

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

new_node->data = data;

new_node->next = NULL;

return new_node;

// Function to count the number of nodes in a singly linked list

int countNodes(struct Node* head) {

int count = 0;

struct Node* current = head;

// Traverse the linked list until the end (current is NULL)

while (current != NULL) {

count++;

current = current->next;

return count;

// Function to print the contents of the linked list (optional)

void printList(struct Node* head) {

while (head != NULL) {

printf("%d ", head->data);

head = head->next;

printf("\n");

int main() {
/* Create a sample linked list */

struct Node* head = newNode(1);

head->next = newNode(2);

head->next->next = newNode(3);

printf("Number of nodes: %d\n", countNodes(head));

/* Optional: Print the linked list */

printList(head);

return 0;

14. Write an Algorithm to traverse a singly linked list?

#include <stdio.h>

#include <stdlib.h>

struct Node {

int data;

struct Node* next;

};

// Function to create a new node (optional, can be included if needed)

struct Node* newNode(int data) {

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

new_node->data = data;

new_node->next = NULL;

return new_node;

}
// Function to traverse the linked list

void traverse(struct Node* head) {

struct Node* current = head; // Start from the head node

// Traverse the list until the end (current is NULL)

while (current != NULL) {

printf("%d ", current->data);

current = current->next;

printf("\n"); // Print a newline after traversing the list

int main() {

/* Create a sample linked list (optional, can be modified) */

struct Node* head = newNode(1);

head->next = newNode(2);

head->next->next = newNode(3);

printf("Linked List: ");

traverse(head);

return 0;

15. Write an Algorithm to insert a node a) in the beginning b) in the end of a singly linked list c)
after a specific node?

#include <stdio.h>

#include <stdlib.h>

struct Node {
int data;

struct Node* next;

};

// Function to create a new node (optional, can be included if needed)

struct Node* newNode(int data) {

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

new_node->data = data;

new_node->next = NULL;

return new_node;

// Function to insert a node at the beginning

void insertAtBeginning(struct Node** head_ref, int new_data) {

struct Node* new_node = newNode(new_data);

new_node->next = (*head_ref);

(*head_ref) = new_node;

// Function to insert a node at the end

void insertAtEnd(struct Node** head_ref, int new_data) {

struct Node* new_node = newNode(new_data);

if (*head_ref == NULL) {

(*head_ref) = new_node;

return;

struct Node* last = *head_ref;

while (last->next != NULL) {

last = last->next;
}

last->next = new_node;

// Function to insert a node after a specific node

void insertAfter(struct Node* prev_node, int new_data) {

if (prev_node == NULL) {

printf("The given previous node cannot be NULL");

return;

struct Node* new_node = newNode(new_data);

new_node->next = prev_node->next;

prev_node->next = new_node;

// Function to print the linked list (optional)

void printList(struct Node* node) {

while (node != NULL) {

printf("%d ", node->data);

node = node->next;

printf("\n");

int main() {

/* Create a sample linked list (optional, can be modified) */

struct Node* head = newNode(1);

head->next = newNode(2);

head->next->next = newNode(3);

printf("Original List: ");


printList(head);

// Insert at beginning

insertAtBeginning(&head, 0);

printf("List after insertion at beginning: ");

printList(head);

// Insert at end

insertAtEnd(&head, 4);

printf("List after insertion at end: ");

16. Write an algorithm to delete a node from a) beginning b) end c) specific key element of a
singly linked list?

#include <stdio.h>

#include <stdlib.h>

struct Node {

int data;

struct Node* next;

};

// Function to create a new node (optional, can be included if needed)

struct Node* newNode(int data) {

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

new_node->data = data;

new_node->next = NULL;

return new_node;

// Function to delete a node from the beginning

void deleteFromBeginning(struct Node** head_ref) {


if (*head_ref == NULL) {

return; // List is empty

struct Node* temp = *head_ref;

*head_ref = (*head_ref)->next;

free(temp);

// Function to delete a node from the end

void deleteFromEnd(struct Node** head_ref) {

if (*head_ref == NULL) {

return; // List is empty

struct Node* current = *head_ref;

struct Node* prev = NULL;

while (current->next != NULL) {

prev = current;

current = current->next;

// Handle single node list

if (prev == NULL) {

free(*head_ref);

*head_ref = NULL;

return;

prev->next = NULL;
free(current);

// Function to delete a node with a specific key

void deleteNode(struct Node** head_ref, int key) {

// Handle empty list

if (*head_ref == NULL) {

return;

// Check if the head node needs to be deleted

if ((*head_ref)->data == key) {

deleteFromBeginning(head_ref);

return;

// Use two pointers, current and prev, to traverse the list

struct Node* current = *head_ref;

struct Node* prev = NULL;

while (current != NULL) {

// If key is found

if (current->data == key) {

// Link previous node with the node after the current

prev->next = current->next;

// Free the memory of the deleted node

free(current);

return;

prev = current;
current = current->next;

// Key not found in the list

printf("Key %d not found in the linked list\n", key);

// (Optional) Function to print the linked list

void printList(struct Node* node) {

while (node != NULL) {

printf("%d ", node->data);

node = node->next;

printf("\n");

int main() {

// Create a linked list

struct Node* head = newNode(10);

head->next = newNode(20);

head->next->next = newNode(30);

head->next->next->next = newNode(40);

printf("Original List: ");

printList(head);

// Delete node with key 20

deleteNode(&head, 20);

printf("List after deletion: ");

printList(head);
return 0;

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