ADVERTISEMENT
ADVERTISEMENT

Ruby program to search an item into the array using binary search

Ruby Example: Write a program to search an item into the array using binary search.
Submitted by Nidhi, on January 20, 2022

Problem Solution:

In this program, we will create an array of integer elements. Then we will read an item from the user to search into the array using binary search and print the index of the item in the array.

In binary searching, we compare an item by finding the middle element. It is more efficient than linear search. But we use binary search in the case of the sorted array only.

Program/Source Code:

The source code to search an item into the array using binary search is given below. The given program is compiled and executed successfully.

# Ruby program to search an item into the array 
# using binary search

arr = [12,23,39,57,68];

item =   0;
flag =   -1;

first = 0;
last = arr.size() - 1;
middle = (first + last) / 2;

print "Enter item: ";
item = gets.chomp.to_i;  

while(first<=last)
    if(arr[middle]<item)
        first=middle + 1;
    elsif(arr[middle]==item)
        flag=middle;
        break;
    else
        last = middle - 1;
    end
    middle = (first + last) / 2;
end

if(flag>=0)
    print "Item found at index: ",flag,"\n"; 
else
    print "Item not found\n"; 
end

Output:

Enter item: 57
Item found at index: 3

Explanation:

In the above program, we created an array of integer elements. Then we read an item from the user to search into the sorted array using a binary search mechanism. After that, we printed the index of the item in the array, if the item was found. Otherwise, we printed the "Item not found" message.

Ruby Arrays Programs »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.