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

2nd assignment algorithm

Uploaded by

dangech0922
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

2nd assignment algorithm

Uploaded by

dangech0922
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Mettu university

• Colege of Engineering and thechnology


• Department of computer science
 Group assignment for Data structure and algorithm

Group information
Name__________________________id
1.
2.
3.
4.
1. write a c++ program which can accept list of names from the user
and then search a particular name from the list by using binary
searching algorithm.

#include <iostream>// This header file allows input and output


operations, such as reading from the standard input and writing
to the standard output.
#include <vector>// It is used to create a dynamic array to store
the list of names.
#include <algorithm>//his header file provides various
algorithms, including sorting and searching functions. It is used
to sort the list of names and perform the binary search.

// Function to perform binary search


int binarySearch(std::vector<std::string>& names, const
std::string& name) {
int left = 0;
int right = names.size() - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

// Check if the name is present at mid


if (names[mid] == name) {
return mid;
}

// If name is greater, ignore left half


if (names[mid] < name) {
left = mid + 1;
}
// If name is smaller, ignore right half
else {
right = mid - 1;
}
}

// Name not found


return -1;
}

int main() {
std::vector<std::string> names;
int n;
std::string nameToSearch;

// Accept the number of names from the user


std::cout << "Enter the number of names: ";
std::cin >> n;

// Accept the list of names from the user


std::cout << "Enter the names: ";
for (int i = 0; i < n; i++) {
std::string name;
std::cin >> name;
names.push_back(name);
}

// Sort the list of names


std::sort(names.begin(), names.end());

// Accept the name to search from the user


std::cout << "Enter the name to search: ";
std::cin >> nameToSearch;

// Perform binary search


int index = binarySearch(names, nameToSearch);

// Display the result


if (index != -1) {
std::cout << "Name found at index " << index << std::endl;
} else {
std::cout << "Name not found" << std::endl;
}

return 0;
}

You might also like