0% found this document useful (0 votes)
20 views14 pages

DS Solutions

The document provides a comprehensive overview of data structures, including definitions and examples of linear and non-linear data structures, sorting and searching algorithms, and abstract data types (ADTs). It also covers linked lists, their advantages and disadvantages, and various operations such as insertion and deletion. Additionally, it includes code snippets for linear and binary search algorithms, as well as sorting techniques like selection sort.

Uploaded by

ruttalakarthik3
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)
20 views14 pages

DS Solutions

The document provides a comprehensive overview of data structures, including definitions and examples of linear and non-linear data structures, sorting and searching algorithms, and abstract data types (ADTs). It also covers linked lists, their advantages and disadvantages, and various operations such as insertion and deletion. Additionally, it includes code snippets for linear and binary search algorithms, as well as sorting techniques like selection sort.

Uploaded by

ruttalakarthik3
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/ 14

Unit-1: Solutions:

Short Answers

1. Define data structure?


A data structure is a way of organizing and storing data in a computer so that it can be accessed and modified efficiently.

2. What is linear data structure and non-linear data structure? Give some examples?
Linear data structure: Data elements are arranged in a sequential order. Examples: Arrays, Linked Lists, Stacks, Queues.
Non-linear data structure: Data elements are not arranged in a sequential order. Examples: Trees, Graphs.

3. Define sorting? List out any two applications?


Sorting is the process of arranging data in a specific order (ascending or descending).
Applications:
- Sorting names in a phonebook.
- Sorting products by price on an e-commerce website.

4. What is searching? List out any two applications.


Searching is the process of finding a specific element in a collection of data.
Applications:
- Finding a book in a library.
- Searching for a specific record in a database.

5. What is ADT (abstract data type)?


An Abstract Data Type (ADT) is a mathematical model for data types. It defines the behavior of a data structure in terms of possible values,
operations, and the behavior of these operations. Examples: Stack, Queue, List.
6. What does time complexity and space complexity of an algorithm represent?
Time complexity: Measures the amount of time an algorithm takes to run as a function of the input size.
Space complexity: Measures the amount of memory an algorithm uses as a function of the input size.

7. Contrast linear search with binary search.


Linear search: Checks each element one by one. Works on both sorted and unsorted data. Time complexity: O(n).
Binary search: Works only on sorted data. It repeatedly divides the search interval in half. Time complexity: O(log n).

8. Write the time complexity (best, average, worst case) of bubble sort, selection sort, and insertion sort.
Bubble sort: Best - O(n), Average - O(n²), Worst - O(n²).
Selection sort: Best - O(n²), Average - O(n²), Worst - O(n²).
Insertion sor: Best - O(n), Average - O(n²), Worst - O(n²).

9.List out various operations that can be performed on data structures


- Insertion, Deletion, Traversal, Searching, Sorting, Merging, Updating.

---

Long Answers

1. Illustrate a program to search for an element in the given list of numbers using linear search approach.
#include <stdio.h>

int linearSearch(int arr[], int n, int target) {


for (int i = 0; i < n; i++) {
if (arr[i] == target) {
return i; // Return the index of the target element
}
}
return -1; // Return -1 if the target is not found
}

int main() {
int arr[] = {21, 54, 32, 67, 2, 45, 21, 45, 8};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 21;
int result = linearSearch(arr, n, target);
if (result != -1) {
printf("Element found at index: %d\n", result);
} else {
printf("Element not found\n");
}
return 0;
}

2. Illustrate a program to search for an element in the given list of numbers using binary search approach.
#include <stdio.h>

int binarySearch(int arr[], int left, int right, int target) {


while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Return the index of the target element
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // Return -1 if the target is not found
}

int main() {
int arr[] = {12, 16, 17, 19, 20, 22, 24, 29, 30, 32, 37};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 32;
int result = binarySearch(arr, 0, n - 1, target);
if (result != -1) {
printf("Element found at index: %d\n", result);
} else {
printf("Element not found\n");
}
return 0;
}

3. Explain linear search algorithm in detail for the given elements: 21, 54, 32, 67, 2, 45, 21, 45, 8. Consider 21 as a search element.
- Start from the first element (21).
- Compare 21 with the target (21). They match, so the search is successful at index 0.
- If the target were not found, the algorithm would continue checking each element until the end of the list.

4. Outline an algorithm to implement Binary Search technique. Use the algorithm to search 32 in the following list of elements. Explain the
process at each step. 12, 16, 17, 19, 20, 22, 24, 29, 30, 32, 37.
Step 1: Initialize `left = 0`, `right = 10`.
Step 2: Calculate `mid = (0 + 10) / 2 = 5`. Compare `arr[5] = 22` with 32. Since 22 < 32, set `left = mid + 1 = 6`.
Step 3: Calculate `mid = (6 + 10) / 2 = 8`.

Compare `arr[8] = 30` with 32. Since 30 < 32,

set left = mid + 1 = 9;


Step 4: Calculate `mid = (9 + 10) / 2 = 9; Compare `arr[9] = 32` with 32. They match, so the search is successful at index 9.

5. Illustrate a program to sort the given elements using Selection Sort.


#include <stdio.h>

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


for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

int main() {
int arr[] = {20, 12, 10, 15, 2};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

6. Illustrate Selection sort to identify how many iterations required to place 12 in its correct position for the unsorted list 20, 12, 10, 15, 2.
iteration 1: Find the smallest element (2) and swap it with the first element (20). List: [2, 12, 10, 15, 20].
Iteration 2: Find the next smallest element (10) and swap it with the second element (12). List: [2, 10, 12, 15, 20].
Iteration 3: 12 is already in its correct position.
- Total iterations required: 2

Unit-2: Solutions**

Short Answers

1. What is a linked list?


A linked list is a linear data structure where each element (called a node) contains data and a pointer to the next node. Unlike arrays, linked lists
are dynamic in size.
2. What is a node in a linked list?
A node is the basic unit of a linked list. It contains two parts:
-Data: The value stored in the node.
Pointer: A reference to the next node in the list.

3. List out the applications of linked lists.


- Implementing stacks and queues.
- Dynamic memory allocation.
- Representing sparse matrices.
- Used in graph algorithms like adjacency lists.

4. Discuss the purpose of the head node in linked lists.


The head node is the starting point of a linked list. It points to the first node in the list and is used to traverse the entire list.

5.Discuss the drawback of a singly linked list compared to a doubly linked list.
Singly linked list: Can only traverse in one direction (forward).
Doubly linked list: Can traverse in both directions (forward and backward), making operations like deletion and insertion more efficient.

6. Discuss the differences between arrays and linked lists.


Arrays: Fixed size, contiguous memory allocation, faster access time (O(1)).
Linked lists: Dynamic size, non-contiguous memory allocation, slower access time (O(n)).

7. Why are linked lists called dynamic data structures?


Linked lists are called dynamic because their size can grow or shrink during program execution, unlike arrays, which have a fixed size.

8. Compare singly linked lists and circular linked lists.


Singly linked list: The last node points to `NULL`.
Circular linked list: The last node points back to the first node, forming a loop.

9. What is a doubly linked list?


A doubly linked list is a linked list where each node contains two pointers: one to the next node and one to the previous node.

---

Long Answer Type

1. Discuss the advantages and disadvantages of linked lists.


Advantages:
- Dynamic size.
- Efficient insertion and deletion.
- No memory wastage.
Disadvantages:
- Slower access time (O(n)).
- Extra memory required for pointers.
- Complex implementation compared to arrays.

2. Design a code snippet to traverse singly linked list elements.


#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

void traverseLinkedList(struct Node* head) {


struct Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

int main() {
// Creating a sample linked list: 10 -> 20 -> 30 -> NULL
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
struct Node* third = (struct Node*)malloc(sizeof(struct Node));

head->data = 10;
head->next = second;
second->data = 20;
second->next = third;
third->data = 30;
third->next = NULL;

// Traversing the linked list


traverseLinkedList(head);

// Free memory
free(head);
free(second);
free(third);

return 0;
}
```

3. Discuss different cases of insertion operations on singly linked lists. Design a pseudo code for the same.
Insertion at the beginning:

void insertAtBeginning(struct Node** head, int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}

Insertion at the end:

void insertAtEnd(struct Node** head, int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;

if (*head == NULL) {
*head = newNode;
return;
}
struct Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
```
Insertion at a specific position:

void insertAtPosition(struct Node* head, int data, int position) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;

if (position == 1) {
newNode->next = *head;
*head = newNode;
return;
}

struct Node* temp = *head;


for (int i = 1; i < position - 1 && temp != NULL; i++) {
temp = temp->next;
}

if (temp == NULL) {
printf("Position out of range\n");
return;
}
newNode->next = temp->next;
temp->next = newNode;
}

4. Discuss different cases of deletion operations on singly linked lists. Design a code snippet for the same.
Deletion at the beginning:

void deleteAtBeginning(struct Node** head) {


if (*head == NULL) {
printf("List is empty\n");
return;
}
struct Node* temp = *head;
*head = (*head)->next;
free(temp);
}

Deletion at the end:

void deleteAtEnd(struct Node** head) {


if (*head == NULL) {
printf("List is empty\n");
return;
}
if ((*head)->next == NULL) {
free(*head);
*head = NULL;
return;
}
struct Node* temp = *head;
while (temp->next->next != NULL) {
temp = temp->next;
}
free(temp->next);
temp->next = NULL;
}

-Deletion at a specific position:

void deleteAtPosition(struct Node** head, int position) {


if (*head == NULL) {
printf("List is empty\n");
return;
}
struct Node* temp = *head;
if (position == 1) {
*head = temp->next;
free(temp);
return;
}
for (int i = 1; i < position - 1 && temp != NULL; i++) {
temp = temp->next;
}
if (temp == NULL || temp->next == NULL) {
printf("Position out of range\n");
return;
}
struct Node* nodeToDelete = temp->next;
temp->next = nodeToDelete->next;
free(nodeToDelete);
}
```

5.With neat diagrams, explain the following operations in a singly linked list data structure
-Insert element at the beginning:
- Create a new node.
- Point the new node’s `next` to the current head.
- Update the head to point to the new node.
- Insert element at the end:
- Traverse to the last node.
- Point the last node’s `next` to the new node.
- Set the new node’s `next` to `NULL`.
- Insert the specified element:
- Traverse to the node before the desired position.
- Point the new node’s `next` to the next node.
- Update the previous node’s `next` to point to the new node.
- Search the given element:
- Traverse the list and compare each node’s data with the target value.
- Return the position if found, otherwise return `-1`.
Sort the given list:
-Use sorting algorithms like Bubble Sort

or Merge Sort to rearrange the nodes based on their data values.

You might also like