Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

DSU Unit 2 Q and A

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

UNIT-2 Searching and Sorting

1. Describe the working of Bubble sort method with an example.


Bubble Sort is a simple comparison-based sorting algorithm. It repeatedly
steps through the list, compares adjacent elements, and swaps them if they are
in the wrong order. This process is repeated until the list is sorted.
How Bubble Sort Works
1. Starting Point: Begin with the first element of the array.
2. Compare Adjacent Elements: Compare the current element with the next
one.
- If the current element is greater than the next element, swap them.
- If not, move to the next pair of elements.
3. Repeat Process: Continue this process for all elements in the array. By the
end of the first pass, the largest element will have "bubbled up" to its correct
position at the end of the array.
4. Next Pass: Repeat the process for the rest of the array, excluding the last
element (which is already sorted).
5. Continue Until Sorted: The algorithm continues making passes through
the array until no swaps are needed, indicating that the array is sorted.
Example: Bubble Sort on an Array
Consider an array: ` [5, 2, 9, 1, 5, 6] `
Pass 1:
- Compare `5` and `2`. Since `5 > 2`, swap them: `[2, 5, 9, 1, 5, 6]`
- Compare `5` and `9`. No swap needed: `[2, 5, 9, 1, 5, 6]`
- Compare `9` and `1`. Since `9 > 1`, swap them: `[2, 5, 1, 9, 5, 6]`
- Compare `9` and `5`. Since `9 > 5`, swap them: `[2, 5, 1, 5, 9, 6]`
- Compare `9` and `6`. Since `9 > 6`, swap them: `[2, 5, 1, 5, 6, 9]`
At the end of the first pass, the largest element (`9`) has bubbled up to its
correct position.
Pass 2:
- Compare `2` and `5`. No swap needed: `[2, 5, 1, 5, 6, 9]`
- Compare `5` and `1`. Since `5 > 1`, swap them: `[2, 1, 5, 5, 6, 9]`
- Compare `5` and `5`. No swap needed: `[2, 1, 5, 5, 6, 9]`
- Compare `5` and `6`. No swap needed: `[2, 1, 5, 5, 6, 9]`
At the end of the second pass, the second largest element (`6`) has bubbled up
to its correct position.
Pass 3:
- Compare `2` and `1`. Since `2 > 1`, swap them: `[1, 2, 5, 5, 6, 9]`
- Compare `2` and `5`. No swap needed: `[1, 2, 5, 5, 6, 9]`
- Compare `5` and `5`. No swap needed: `[1, 2, 5, 5, 6, 9]`
At the end of the third pass, no swaps are needed, indicating that the array is
now sorted. (for program see CW)
2. Find the position of element 30 using Binary search method in array
A = {10, 5, 20, 25, 8, 30, 40}
#include <stdio.h>
int binarySearch(int arr[], int size, int target) {
int left = 0, right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid; // Return the index if found
}
if (arr[mid] < target) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return -1;
}
int main() {
int A[] = {5, 8, 10, 20, 25, 30, 40};
int size = sizeof(A) / sizeof(A[0]);
int target = 30;
int position = binarySearch(A, size, target);
if (position != -1) {
printf("Element %d found at position %d.\n", target, position
+ 1); // Position is index + 1
} else {
printf("Element %d not found in the array.\n", target);
}
return 0;
}
3. Write a ‘C’ program to calculate the factorial of number using
recursion.
#include <stdio.h>
int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
else {
return n * factorial(n - 1);
}
}
int main() {
int number;
printf("Enter a positive integer: ");
scanf("%d", &number);
if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
int result = factorial(number);
printf("Factorial of %d is %d.\n", number, result);
}
return 0;
}
4. Describe the working of Selection Sort Method. Also sort given input
list in ascending order using selection sort. Input list: 50, 24, 5, 12, 30
Selection Sort is a simple comparison-based sorting algorithm. It works by
repeatedly finding the minimum element from the unsorted portion of the list
and swapping it with the first element of the unsorted portion. This process is
repeated, reducing the size of the unsorted portion by one element each time,
until the entire list is sorted.
How Selection Sort Works
1. Initialization: Start with the first element of the array as the minimum.
2. Find Minimum: Traverse the unsorted portion of the array to find the
minimum element.
3. Swap: Swap the minimum element found with the first element of the
unsorted portion.
4. Repeat: Move the boundary of the sorted portion one element to the right
and repeat the process for the remaining unsorted elements.
5. Continue: Continue until the entire array is sorted.

Example: Sorting the List `[50, 24, 5, 12, 30]` Using Selection Sort
Initial List:
[50, 24, 5, 12, 30]

Step-by-Step Sorting:
Pass 1:
- Initial Array: `[50, 24, 5, 12, 30]`
- Find Minimum: The minimum element in the list is `5`.
- Swap: Swap `5` with the first element (`50`).
- Array After Swap: `[5, 24, 50, 12, 30]`
Pass 2:
- Array: `[5, 24, 50, 12, 30]`
- Find Minimum: The minimum element in the remaining unsorted portion
`[24, 50, 12, 30]` is `12`.
- Swap: Swap `12` with the second element (`24`).
- Array After Swap: `[5, 12, 50, 24, 30]`
Pass 3:
- Array: `[5, 12, 50, 24, 30]`
- Find Minimum: The minimum element in the remaining unsorted portion
`[50, 24, 30]` is `24`.
- Swap: Swap `24` with the third element (`50`).
- Array After Swap: `[5, 12, 24, 50, 30]`
Pass 4:
- Array: `[5, 12, 24, 50, 30]`
- Find Minimum: The minimum element in the remaining unsorted portion
`[50, 30]` is `30`.
- Swap: Swap `30` with the fourth element (`50`).
- Array After Swap: `[5, 12, 24, 30, 50]`
Final Sorted Array:
[5, 12, 24, 30, 50]

5. Explain complexity of following algorithms in terms of time and


space: (i) Binary search (ii) Bubble sort
1. Binary Search
Time Complexity:
- Best Case: O(1)
- This occurs when the target element is at the middle of the array
on the first comparison.
- Average and Worst Case: O(log n)
- In each step, Binary Search reduces the search space by half.
This logarithmic nature of division makes the time complexity
`O(log n)`, where `n` is the number of elements in the array.
Space Complexity:
- Iterative Version: O(1)
- Binary Search uses a constant amount of space for its variables,
as it only needs pointers or indices to track the current segment of
the array being searched.
- Recursive Version: O(log n)
- In the recursive approach, each function call adds a new layer to
the call stack, leading to a space complexity of `O(log n)`.

2. Bubble Sort
Time Complexity:
- Best Case: O(n)
-If the array is already sorted, Bubble Sort can terminate early
after a single pass through the array. This is possible because the
algorithm can detect that no swaps were made in a full pass,
indicating that the list is sorted.
- Average and Worst Case: O(n^2)
- In the worst case (e.g., when the array is sorted in reverse order),
Bubble Sort will compare each pair of elements in each pass,
leading to `n(n-1)/2` comparisons and swaps, which simplifies to
`O(n^2)`.

Space Complexity:
- O(1)
- Bubble Sort is an in-place sorting algorithm, meaning it requires
only a constant amount of additional memory beyond the input
array itself. It uses a few extra variables for swapping elements, but
no additional space proportional to the input size is needed.
6. Sort the following number in ascending order using bubble sort.
Given numbers as follows: 475, 15, 513, 6753, 45, 118.
#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
void printArray(int arr[], int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {475, 15, 513, 6753, 45, 118};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
bubbleSort(arr, n);
printf("Sorted array in ascending order: \n");
printArray(arr, n);
return 0;
}

7. Define Searching. What are its types?


Searching is the process of finding the location of a specific
element within a data structure, such as an array or a list. There are
two primary types of searching:

1. Linear Search: Sequentially checks each element until the


target is found or the list ends.
2. Binary Search: Efficiently searches a sorted list by repeatedly
dividing the search interval in half.
8. Sort the following numbers in ascending order using Insertion sort:
{25, 15, 4, 103, 62, 9} and write the output after each iteration.
#include <stdio.h>
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
printf("Iteration %d: ", i);
for (int k = 0; k <= i; k++) {
printf("%d ", arr[k]);
}
printf("\n");
}
}
int main() {
int arr[] = {25, 15, 4, 103, 62, 9};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
insertionSort(arr, n);
printf("Sorted array in ascending order: \n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output: -
Original array:
25 15 4 103 62 9
Iteration 1: 15 25
Iteration 2: 4 15 25
Iteration 3: 4 15 25 103
Iteration 4: 4 15 25 62 103
Iteration 5: 4 9 15 25 62 103
Sorted array in ascending order:
4 9 15 25 62 103
9. Differentiate between Binary search and Linear search with respect
to any four parameters.
10. Find the position of element 29 using Binary search method in an
array given as: {11, 5, 21, 3, 29, 17, 2, 43}
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int target) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {11, 5, 21, 3, 29, 17, 2, 43};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 29;
bubbleSort(arr, n);
int result = binarySearch(arr, 0, n-1, target);
if (result != -1)
printf("Element %d is present at index %d in the sorted array.\n", target,
result);
else
printf("Element %d is not present in the array.\n", target);
return 0;
}

Output: -
Element 29 is present at index 6 in the sorted array.
11. Implement a ‘C’ program to search a particular data from the given
array using Linear Search.

#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 if target is found
}
}
return -1; // Return -1 if target is not found
}
int main() {
int arr[] = {23, 45, 12, 67, 34, 89, 90, 11};
int n = sizeof(arr) / sizeof(arr[0]);
int target;
printf("Enter the element to search: ");
scanf("%d", &target);
int result = linearSearch(arr, n, target);
if (result != -1)
printf("Element %d is present at index %d in the array.\n",
target, result);
else
printf("Element %d is not present in the array.\n", target);
return 0;
}

Output: -
Enter the element to search: 67
Element 67 is present at index 3 in the array.
Enter the element to search: 50
Element 50 is not present in the array.
12. Find the position of element 21 using Binary Search method in Array
‘A’ given below: A = {11, 5, 21, 3, 29, 17, 2, 45}
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int target) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target)
return mid;
if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {11, 5, 21, 3, 29, 17, 2, 45};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 21;
bubbleSort(arr, n);
int result = binarySearch(arr, 0, n-1, target);
if (result != -1)
printf("Element %d is present at index %d in the sorted array.\n", target,
result);
else
printf("Element %d is not present in the array.\n", target);
return 0;
}
Output: -
Element 21 is present at index 5 in the sorted array.
13. Elaborate the steps for performing selection sort for given elements
of array. A = {37, 12, 4, 90, 49, 23, –19}
Steps for Performing Selection Sort:
1. Initial Array: `{37, 12, 4, 90, 49, 23, -19}`
2. Step 1 (First Iteration):
- Current Array: `{37, 12, 4, 90, 49, 23, -19}`
- Unsorted Portion: `{37, 12, 4, 90, 49, 23, -19}`
- Find Minimum: The smallest element in the unsorted portion is `-19`.
- Swap: Swap `-19` with the first element of the unsorted portion (`37`).
- Array After Step 1: `{-19, 12, 4, 90, 49, 23, 37}`
3. Step 2 (Second Iteration):
- Current Array: `{-19, 12, 4, 90, 49, 23, 37}`
- Unsorted Portion: `{12, 4, 90, 49, 23, 37}`
- Find Minimum: The smallest element in the unsorted portion is `4`.
- Swap: Swap `4` with the first element of the unsorted portion (`12`).
- Array After Step 2: `{-19, 4, 12, 90, 49, 23, 37}`
4. Step 3 (Third Iteration):
- Current Array: `{-19, 4, 12, 90, 49, 23, 37}`
- Unsorted Portion: `{12, 90, 49, 23, 37}`
- Find Minimum: The smallest element in the unsorted portion is `12`.
- Swap: Since `12` is already in the correct position, no swap is needed.
- Array After Step 3: `{-19, 4, 12, 90, 49, 23, 37}`
5. Step 4 (Fourth Iteration)**:
- Current Array: `{-19, 4, 12, 90, 49, 23, 37}`
- Unsorted Portion: `{90, 49, 23, 37}`
- Find Minimum: The smallest element in the unsorted portion is `23`.
- Swap: Swap `23` with the first element of the unsorted portion (`90`).
- Array After Step 4: `{-19, 4, 12, 23, 49, 90, 37}`
6. Step 5 (Fifth Iteration):
- Current Array: `{-19, 4, 12, 23, 49, 90, 37}`
- Unsorted Portion: `{49, 90, 37}`
- Find Minimum: The smallest element in the unsorted portion is `37`.
- Swap: Swap `37` with the first element of the unsorted portion (`49`).
- Array After Step 5: `{-19, 4, 12, 23, 37, 90, 49}`
7. Step 6 (Sixth Iteration):
- Current Array: `{-19, 4, 12, 23, 37, 90, 49}`
- Unsorted Portion: `{90, 49}`
- Find Minimum: The smallest element in the unsorted portion is `49`.
- Swap: Swap `49` with the first element of the unsorted portion (`90`).
- Array After Step 6: `{-19, 4, 12, 23, 37, 49, 90}`
8. Step 7 (Final Step):
- Current Array: `{-19, 4, 12, 23, 37, 49, 90}`
- Unsorted Portion: `{90}` (only one element left, so it's already in its correct
position).
Final Sorted Array: `{-19, 4, 12, 23, 37, 49, 90}`
14.State the following terms: (i)searching(ii)sorting
(i) Searching: Searching is the process of locating a specific element or value
within a data structure, such as an array or list. It involves examining each
element to determine whether it matches the desired value. Common searching
algorithms include Linear Search and Binary Search.
(ii) Sorting: Sorting is the process of arranging elements in a data structure in
a specific order, typically ascending or descending. The goal is to organize
data for efficient retrieval and processing. Common sorting algorithms include
Bubble Sort, Selection Sort, and Merge Sort.
15. Find location of element 20 by using binary search algorithm in the list
given below: 10, 20, 30, 40, 50, 60, 70, 80
Binary Search Algorithm
1. Initialize: Set `low` to the first index (`0`) and `high` to the last index (`7`).
2. Iterate:
- Calculate the middle index (`mid`) using `mid = low + (high - low) / 2`.
- Compare the target value with the element at the `mid` index.
- Adjust `low` or `high` based on the comparison.
3. Repeat the steps until the target is found or the search space is exhausted.
C Program to Perform Binary Search
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int target) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target)
return mid; // Return the index if target is found
if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main() {
int arr[] = {10, 20, 30, 40, 50, 60, 70, 80};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 20;
int result = binarySearch(arr, 0, n - 1, target);
if (result != -1)
printf("Element %d is present at index %d.\n", target, result);
else
printf("Element %d is not present in the array.\n", target);
return 0;
}
Output:
Element 20 is present at index 1.
16. Describe working of linear search with example.
Linear Search: Description and Example
Linear Search is a straightforward algorithm used to find a specific
element in an array or list by examining each element sequentially until
the target element is found or the end of the list is reached. It is simple
and does not require the array to be sorted.
Working of Linear Search
1. Initialization:
- Start from the first element of the array or list.
- Initialize an index to keep track of the current position in the list.
2. Iteration:
- Compare the current element with the target element.
- If they match, return the index of the current element.
- If not, move to the next element.
3. Termination:
- If the end of the list is reached without finding the target, return `-1`
or an indicator that the element is not present.

C Program for Linear Search


#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 if target is found
}
}
return -1; // Return -1 if target is not found
}
int main() {
int arr[] = {34, 7, 23, 32, 5, 16};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 32;
int result = linearSearch(arr, n, target);
if (result != -1)
printf("Element %d is present at index %d.\n", target, result);
else
printf("Element %d is not present in the array.\n", target);
return 0;
}
17. Write a ‘C’ program for insertion sort. Sort the following array
using insertion sort: 30 10 40 50 20 45

#include <stdio.h>
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {30, 10, 40, 50, 20, 45};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array:\n");
printArray(arr, n);
insertionSort(arr, n);
printf("Sorted array:\n");
printArray(arr, n);
return 0;
}
18. Explain the working of Binary search with an example.
Binary Search is an efficient algorithm for finding a target value within a
sorted array. It repeatedly divides the search interval in half, significantly
reducing the number of comparisons needed compared to linear search.
Working of Binary Search
1. Initialize:
- Set two pointers: `low` (the starting index of the array) and `high` (the
ending index of the array).
2. Iterate:
- Calculate the middle index (`mid`) of the current search range.
- Compare the target value with the element at the `mid` index:
- If the target is equal to the element at `mid`, the target is found, and the
index is returned.
- If the target is less than the element at `mid`, adjust the `high` pointer to
`mid - 1` (search in the left half).
- If the target is greater than the element at `mid`, adjust the `low` pointer
to `mid + 1` (search in the right half).
3. Repeat:
- Continue the above steps until the `low` pointer exceeds the `high` pointer.
4. Terminate:
- If the target is not found and the search range is exhausted (`low` > `high`),
return `-1` or an indicator that the target is not present.
Example: -
Array: `{10, 20, 30, 40, 50, 60, 70, 80}`
Target Element: `25` Steps:-
1. Initialization:
- `low = 0`
- `high = 7` (index of the last element)
2. First Iteration:
- Calculate `mid`: `mid = low + (high - low) / 2 = 0 + (7 - 0) / 2 = 3`
- Element at `mid`: `arr[3] = 40`
- Compare: `25 < 40`
- Update: Set `high = mid - 1 = 2` (search in the left half)
3. Second Iteration:
- Calculate `mid`: `mid = low + (high - low) / 2 = 0 + (2 - 0) / 2 = 1`
- Element at `mid`: `arr[1] = 20`
- Compare: `25 > 20`
- Update: Set `low = mid + 1 = 2` (search in the right half)
4. Third Iteration:
- Calculate `mid`: `mid = low + (high - low) / 2 = 2 + (2 - 2) / 2 = 2`
- Element at `mid`: `arr[2] = 30`
- Compare: `25 < 30`
- Update: Set `high = mid - 1 = 1` (search in the left half)
5. Termination:
- Check: `low = 2`, `high = 1` (now `low > high`)
- Result: The target element `25` is not present in the array.
19.Sort the following numbers in ascending order using quick sort.
Given numbers 50, 2, 6, 22, 3, 39, 49, 25, 18, 5.
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choose the rightmost element as pivot
int i = low - 1; // Index of the smaller element
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1); // Return the partitioning index
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
// Partition the array
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main()
int arr[] = {50, 2, 6, 22, 3, 39, 49, 25, 18, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array:\n");
printArray(arr, n);
quickSort(arr, 0, n - 1);
printf("Sorted array:\n");
printArray(arr, n);
return 0;}
20. Sort the following numbers in ascending order using Bubble sort.
Given numbers: 29, 35, 3, 8, 11, 15, 56, 12, 1, 4, 85, 5 & write the
output after each interaction.

#include <stdio.h>
void bubbleSort(int arr[], int n) {
int i, j, temp;
int swapped;
for (i = 0; i < n - 1; i++) {
swapped = 0; // Flag to check if any elements were swapped
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = 1;
}
}
printf("Array after pass %d: ", i + 1);
for (int k = 0; k < n; k++) {
printf("%d ", arr[k]);
}
printf("\n");
if (swapped == 0) break;
}
}
int main() {
int arr[] = {29, 35, 3, 8, 11, 15, 56, 12, 1, 4, 85, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
bubbleSort(arr, n);
printf("Sorted array:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

You might also like