Lab Manual: Two Pointers and Sorting in C++ PDF
Document Details
Uploaded by Deleted User
Tags
Summary
This document is a lab manual on two pointers and sorting in C++. It covers the introduction to the two pointers technique and explains how it can be used to solve problems in linear time. It also includes examples and exercises to help understand the concepts.
Full Transcript
**Lab Manual: Two Pointers and Sorting in C++** **Objective** - Understand the Two Pointers technique and Sorting. - Implement the Two Pointers approach to solve common problems. - Practice different sorting algorithms and analyze their efficiency. **Part 1: Two Pointers Technique** **In...
**Lab Manual: Two Pointers and Sorting in C++** **Objective** - Understand the Two Pointers technique and Sorting. - Implement the Two Pointers approach to solve common problems. - Practice different sorting algorithms and analyze their efficiency. **Part 1: Two Pointers Technique** **Introduction** The Two Pointers technique is useful for efficiently solving problems involving arrays or strings. It involves using two pointers at different parts of a data structure and moving them according to certain conditions to solve specific problems in linear time. **When to Use Two Pointers** - To find pairs or subarrays in sorted arrays. - To merge two sorted lists. - For problems with constraints that require optimal, linear solutions. **Example 1: Sum of Two Elements to Target** \#include \ \#include \ \#include \ using namespace std; std::pair\ twoSum(const std::vector\& arr, int target) { int left = 0, right = arr.size() - 1; while (left \< right) { int sum = arr\[left\] + arr\[right\]; if (sum == target) return {left, right}; else if (sum \< target) left++; else right\--; } return {-1, -1}; // Pair not found } int main() { std::vector\ arr = {1, 2, 3, 4, 6}; int target = 6; auto result = twoSum(arr, target); if (result.first != -1) std::cout \