0% found this document useful (0 votes)
5 views

DAA Lab 4

The document outlines four programming problems: sorting an array with elements at most k positions away from their correct position, finding the k-th smallest element in an unsorted array, checking for a pair of elements that sum to a target, and performing insertion and deletion in a Binary Search Tree (BST). Each problem includes a description, algorithm code in C++, analysis of time and space complexity, and optimization suggestions. Complexity analysis tables are provided for each problem to summarize the performance in different cases.

Uploaded by

id.yogeshgarg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

DAA Lab 4

The document outlines four programming problems: sorting an array with elements at most k positions away from their correct position, finding the k-th smallest element in an unsorted array, checking for a pair of elements that sum to a target, and performing insertion and deletion in a Binary Search Tree (BST). Each problem includes a description, algorithm code in C++, analysis of time and space complexity, and optimization suggestions. Complexity analysis tables are provided for each problem to summarize the performance in different cases.

Uploaded by

id.yogeshgarg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Experiment -3

Problems
(1) WAP to sort an Array Where Each Element is at Most k Positions Away From Its
Correct Position(K=3)

Description:
We need to sort an array where each element is at most k positions away from its correct position. A min-
heap (priority queue) is an efficient way to achieve this, as it maintains the smallest element at the top and
helps in placing elements in sorted order efficiently..

Algorithm Code (C++):


void k_sort(vector<int> &arr, int k) {
priority_queue<int, vector<int>, greater<int>>
int main() {
pq(arr.begin(), arr.begin() + k + 1);
vector<int> arr = {6, 5, 3, 2, 8, 10, 9};
int index = 0;
int k = 3;
for (int i = k + 1; i < arr.size(); i++) {
k_sort(arr, k);
arr[index++] = pq.top();
for (int x : arr) cout << x << " ";
pq.pop();
}
pq.push(arr[i]);
Output:
}
while (!pq.empty()) {
arr[index++] = pq.top();
pq.pop();
}
}
Analysis:
 The min-heap stores the first k+1 elements and sorts them as we iterate through the array.
 Extracting the minimum from the heap ensures that elements are placed in the correct order.
Time Complexity:
 Heap operations: Insertion and extraction take O(log k) time.
 Total elements processed: n.
 Overall complexity: O(n log k).
Space Complexity:
 The heap stores at most k+1 elements, requiring O(k) extra space.

Optimization:
- A more efficient method isn’t needed since O(n log k) is optimal for this problem.
- If k is small, we can use an adaptive Insertion Sort (O(nk)), but it's not efficient for larger k
Complexity Analysis Table:

Case Time Complexity Space Complexity

Best Case O(n log k) O(k)


Average Case O(n log k) O(k)

Worst Case O(n log k) O(k)

(2) WAP to find the k-th Smallest Element in an Unsorted Array

Description:
To find the k-th smallest element in an unsorted array, we can use a min-heap (priority queue) for an
efficient approach. Another efficient method is the QuickSelect algorithm, which is an optimized version of
QuickSort for finding the k-th smallest element in O(n) average time.

Algorithm Code (C++): (MIN HEAP)


int kth_smallest(vector<int> &arr, int k) {
int main() {
priority_queue<int> pq;
vector<int> arr = {7, 10, 4, 3, 20, 15};
for (int x : arr) {
int k = 3;
pq.push(x);
cout << kth_smallest(arr, k);
if (pq.size() > k) pq.pop();
}
}
Output:
return pq.top();
}

Analysis:
 We use a max-heap of size k to maintain the smallest k elements.
 The top of the heap gives the k-th smallest element.
Time Complexity:
 Building the heap: O(k)
 Processing remaining elements: O((n-k) log k)
 Total complexity: O(n log k)
Space Complexity:
 The heap stores at most k elements: O(k)

Optimization:

Algorithm Code (C++): (Quick Sort) if (l == r) return arr[l];


int partition(vector<int> &arr, int l, int r) { int pi = partition(arr, l, r);
int pivot = arr[r], i = l; if (pi == k) return arr[pi];
for (int j = l; j < r; j++) return (pi < k) ? quick_select(arr, pi + 1, r, k) :
if (arr[j] <= pivot) swap(arr[i++], arr[j]); quick_select(arr, l, pi - 1, k);
swap(arr[i], arr[r]); int kth_smallest(vector<int> &arr, int k) { return
return i;} quick_select(arr, 0, arr.size() - 1, k - 1); }
int quick_select(vector<int> &arr, int l, int r, int k)
{

Complexity Analysis Table:


Case MIN HEAP QUICK SORT

Worst O(n log k) O(n²) (rare)

Best O(n) O(n)


Average O(n log k) O(n)

(3)2 Sum

Description:
We need to check if there exists a pair of elements in an array whose sum equals the given target. A simple
approach is sorting the array and then using the two-pointer technique, which ensures an O(n log n) time
complexity (due to sorting).

Algorithm Code (C++):


bool has_pair(vector<int> &arr, int target) {
int main() {
sort(arr.begin(), arr.end());
vector<int> arr = {10, 15, 3, 7};
int left = 0, right = arr.size() - 1;
int target = 17;
while (left < right) {
cout << (has_pair(arr, target) ? "True" :
int sum = arr[left] + arr[right];
"False");
if (sum == target) return true;
}Output:
(sum < target) ? left++ : right--;
}
return false;
}

Analysis:
- Sorting takes O(n log n)
- Two-pointer search runs in O(n)
- Total complexity: O(n log n) + O(n) ≈ O(n log n)
Optimization:
1. We could have used map to store elements and then check if totalSum – currElement =
targetElement exists in the map or not as it takes O(1) time but in worst case O(n) space complexity.
Complexity Analysis Table:

Case Time Complexity Space Complexity

Worst O(n log n) O(1)

Best O(n log n) O(1)


Average O(n log n) O(1)

(4) Binary Search Tree Insertion Deletion


Description:
A Binary Search Tree (BST) is a tree data structure where:
The left subtree contains values smaller than the root. The right subtree contains values greater than the
root. Both subtrees are also BSTs.
Operations:
 Insertion: Insert a new node while maintaining BST properties.
 Deletion: Remove a node while maintaining BST properties (3 cases: leaf node, one child, two
children).

Algorithm Code (C++):


Node* insert(Node* root, int key) {
void inorder(Node* root) {
if (!root) return new Node(key);
if (!root) return;
if (key < root->data) root->left = insert(root-
inorder(root->left);
>left, key);
cout << root->data << " ";
else root->right = insert(root->right, key);
inorder(root->right);}
return root;
int main() {
}
Node* root = NULL;
Node* find_min(Node* root) {
root = insert(root, 50);
while (root->left) root = root->left;
insert(root, 30);
return root;
insert(root, 70);
}
insert(root, 20);
Node* delete_node(Node* root, int key) {
insert(root, 40);
if (!root) return root;
insert(root, 60);
if (key < root->data) root->left =
insert(root, 80);
delete_node(root->left, key);
cout << "Inorder before deletion: ";
else if (key > root->data) root->right =
inorder(root);
delete_node(root->right, key);
root = delete_node(root, 50);
else {
cout << "Inorder after deletion: ";
if (!root->left) return root->right;
inorder(root);
if (!root->right) return root->left;
}
Node* temp = find_min(root->right);
Output:
root->data = temp->data;
root->right = delete_node(root->right, temp-
>data);}
return root;
}
Analysis:
- Insertion Complexity: O(h), where h is tree height (O(log n) for balanced BST).
- Deletion Complexity: O(h), due to traversal and restructuring.
- Inorder Traversal Complexity: O(n) (visits each node once).
Complexity Analysis Table:

Operation Best Case Average Case Worst Case

Insertion O(log n) O(log n) O(n) (skewed BST)

Deletion O(log n) O(log n) O(n) (skewed BST)

Search O(log n) O(log n) O(n) (skewed BST)

You might also like