DSU Unit 2 Q and A
DSU Unit 2 Q and A
DSU Unit 2 Q and A
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]
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;
}
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.
#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;
}