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

Linear+Binary+Traverse Array in DSA

The document explains linear and binary search algorithms for finding elements in arrays. Linear search checks each element sequentially with a time complexity of O(n), while binary search divides the array into halves, requiring a sorted array and offering faster performance. It also includes C++ code examples for both search methods and demonstrates array traversal and element modification.

Uploaded by

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

Linear+Binary+Traverse Array in DSA

The document explains linear and binary search algorithms for finding elements in arrays. Linear search checks each element sequentially with a time complexity of O(n), while binary search divides the array into halves, requiring a sorted array and offering faster performance. It also includes C++ code examples for both search methods and demonstrates array traversal and element modification.

Uploaded by

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

4. Searching – Finding an element.

Linear search is a method to find an element in an array by checking


each element one by one until it is found or the search ends.
Time Complexity:
I. O(n) means the time taken increases as the number of elements
(n) increases.
II. In the worst case, we check every element one by one.
Example:
If we have 5 elements, we may check all 5 → O(5) = O(n)
If we have 1000 elements, we may check all 1000 → O(1000) = O(n)
• Best case: We find it at the start → O(1)
• Worst case: We check everything → O(n)
Note:
Larger array = More time needed!
Example: Linear Search
int arr[] = {10, 20, 30, 40, 50};
int key = 50; // Searching for 50
1 Check
1️⃣ arr[0] → 10 (Not the key)
Check
2️⃣ arr[1] → 20 (Not the key)
Check
3️⃣ arr[2] → 30 (Not the key)
Check
4️⃣ arr[3] → 40 (Not the key)
Check
5️⃣ arr[4] → 50 (Found!)
Worst Case Scenario: If key = 60 (not in the array), we
would check every element and still not find it.
#include <iostream> int main() {
using namespace std; int arr[] = {5, 10, 15, 20, 25};
int linearSearch(int arr[], int size, int key) { int size = sizeof(arr) / sizeof(arr[0]); // size
of array
for (int i = 0; i < size; i++) { int key = 20; // Element to search
if (arr[i] == key) int result = linearSearch(arr, size, key); //
return i; // Return index if found Call the function
} if (result != -1)
cout << "Element found at index " << result
return -1; // Return -1 if not found << endl;
} else
cout << "Element not found" << endl;
return 0; }

Output (for key = 20):


Element found at index 3
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
int key = 30;
int index = -1;
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
index = i; Output:
break; } Element found at
} index 2
if (index != -1)
cout << "Element found at index " << index << endl;
else
cout << "Element not found" << endl;
return 0;
Without sizeof() (Manual Mistake):

#include <iostream>
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = 5; // Manual count

// Later, we add more elements but forget to update size


//int arr[] = {10, 20, 30, 40, 50, 60, 70};

std::cout << "Number of elements: " << size << std::endl; //


Wrong output
return 0;
}
2. Binary Search:
Binary Search is a fast search Properties of BS:
method that works by dividing the
list into two halves and checking in
the correct half until the element is ✅ Works only on sorted lists
found or the search ends. ✅ Faster than Linear Search
Example: Searching for 30 in {10, ✅ Divides the list into halves
20, 30, 40, 50} each time
🔹 Look at the middle → If it's not
the key, search left or right →
Found!
🔹 Binary Search Algorithm Steps:
1. Initialize Variables:
•left(starting index) = 0
•right (last index) = size - 1

2. Loop until left ≤ right:


•Find the mid index: mid=left+(right−left)/2
•Compare arr[mid] with the target:
•If arr[mid] == target, return mid (found the element).
•If arr[mid] < target, search the right half (left = mid + 1).
•If arr[mid] > target, search the left half (right = mid - 1).
3. If the loop ends and the element is not found,
return -1.
What does int mid = left + (right - left) / 2;
Example:
This line calculates the middle index
int left = 2, right = 8;
(mid) between left and right in a binary search or
similar algorithm. mid = 2 + (8 - 2) / 2
Why not just use (left + right) / 2? =2+6/2
Using (left + right) / 2 can sometimes cause integer =2+3
=5
overflow if left and right are very large.
How does it work? Why is this method safer?
I. right - left → This calculates the distance between Avoids overflow:
If left = 2,000,000,000 and
left and right.
right = 2,100,000,000, adding them directly (left +
II. (right - left) / 2→ This finds half of that distance. right) could exceed the integer limit.
III. left + (right - left) / 2 → This ensures we start from Note:
left and move halfway to right.
In programming, an integer has a maximum value it
can store. In a 32-bit system, the maximum value for
an integer is 2,147,483,647.
#include <iostream>
using namespace std; int main() {
int binarySearch(int arr[], int size, int key) { int arr[] = {10, 20, 30, 40, 50}; // Must be sorted
int left = 0, right = size - 1; int size = sizeof(arr) / sizeof(arr[0]);
while (left <= right) { int key = 30;
int mid = left + (right - left) / 2; //middle index
if (arr[mid] == key) // If key is found, return index int result = binarySearch(arr, size, key);
return mid;
else if (arr[mid] < key) // If key is greater, search in right if (result != -1)
half
cout << "Element found at index: " <<
left = mid + 1; result << endl;
else // If key is smaller, search in left half else
right = mid - 1; } cout << "Element not found!" << endl;
return -1; // If not found, return -1
} return 0;
Simple C++ Program (Without Using a Function)

#include <iostream> while (left <= right) {


mid = left + (right - left) / 2; // Find the middle index
using namespace std; if (arr[mid] == key) { // If key is found at mid

int main() { index = mid;


break;
int arr[] = {10, 20, 30, 40, 50}; // }
Sorted array
else if (arr[mid] < key) // If key is greater, search in right half
int size = sizeof(arr) /sizeof(arr[0]); left = mid + 1;
// Calculate array size else // If key is smaller, search in left half
right = mid - 1;
int key = 30; // Element to }
search if (index != -1)
int left = 0, right = size - 1, cout << "Element found at index " << index << endl;

mid; // Initialize variables else


cout << "Element not found" << endl;
int index = -1; // Store index if return 0;
found
2. Recursive Binary
Search Function
#include <iostream> int main() {
using namespace std; int arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int binarySearchRecursive(int arr[], int left, int int size = sizeof(arr) / sizeof(arr[0]);
right, int target) {
int target = 23;
if (left > right)
int result = binarySearchRecursive(arr, 0, size - 1,
return -1; // Base case: element not found
target);
int mid = left + (right - left) / 2;
if (result != -1)
if (arr[mid] == target)
cout << "Element found at index " << result <<
return mid; // Found endl;
if (arr[mid] < target)
else
return binarySearchRecursive(arr, mid + 1,
right, target); // Search right half cout << "Element not found" << endl;
return binarySearchRecursive(arr, left, mid - 1, return 0;
target);} // Search left half }
#include <iostream>
Traversing an Array: using namespace std;
Traversing an array means int main() {
accessing each element one by int arr[] = {10, 20, 30, 40, 50}; //
one to read, process, or update it. Array declaration
Types of Array Traversal: int size = sizeof(arr) /
sizeof(arr[0]); // Calculate size of array
1.Reading elements – Simply
cout << "Array elements: ";
printing values.
for (int i = 0; i < size; i++) { // Loop
2.Processing elements – through each element
Performing operations like sum,
cout << arr[i] << " "; // Print
multiplication, or condition- element
based calculations.
}
3.Modifying elements – Updating Output:
return 0; } Array elements:
each value based on conditions. 10 20 30 40 50
Example: Calculating Sum (C++)
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
Output:
int sum = 0;
for (int i = 0; i < size; i++) { Sum of array elements:
sum += arr[i]; // Add each element to 150
sum
}
cout << "Sum of array elements: " <<
sum;
return 0;
}
Doubling Each Element (C++)
#include <iostream>
using namespace std;
int main() {
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
cout << "Modified array: ";
for (int i = 0; i < size; i++) { Output:
arr[i] = arr[i] * 2; // Double each Modified array: 20 40 60 80 100
value
cout << arr[i] << " ";
}
return 0; }

You might also like