CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: General Discussions: General Questions:
Binary serch



Oct 31, 2013, 10:11 AM

Post #1 of 1 (18213 views)
Binary serch Can't Post

Fom additional material given and complete
the function myBinSearch, which should implement a binary search algorithm on a sorted
array. Parameter is on the one hand the search element to be looked for and on the other hand
a reference to the array, where to look for the search element. If the search element is part of
the array, myBinSearch should return the position of the found element, otherwise -1 should
be returned. If you have finished, execute the prepared script and look whether the test cases
give the correct results. [Consider: The algorithm may be only applied to a sorted array, where
the sorting criterion should be the same criterion as used for decisions in binary search].

use strict;
use warnings;

sub myBinSearch {
my $refToSortList=$_[0];
my $search=$_[1];

my @testList = (254324, 213, 2345, 6524, 3475, 81451, 1141);
my @perlSort = sort { $a <=> $b } @testList;

print "\n\n\n";
print "perlSort1: ", join(" ", @perlSort), "\n";
print "\n\n\n";

#Check binary search on sorted array
print "Binary Search:\n";
foreach my $entry (@perlSort){
print $entry-1, ": ", myBinSearch(\@perlSort, $entry-1), "\n";
print $entry, ": ", myBinSearch(\@perlSort, $entry), "\n";
print $entry+1, ": ", myBinSearch(\@perlSort, $entry+1), "\n";
print "\n";


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives