Skip to content

Commit f24b9a6

Browse files
biostaegonSchiele
authored andcommitted
Binary search and selection sort in Perl
* Create 01_binary_search.pl * Typo fixed in 01_binary_search.pl * Create 01_selection_sort.pl
1 parent ea74644 commit f24b9a6

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
sub binary_search {
2+
3+
my ( $item, @list ) = @_;
4+
5+
# The borders inside where we are searching in:
6+
my $low = 0;
7+
my $high = $#list;
8+
9+
# Do that until found or until just one element remains:
10+
while ( $low <= $high ) {
11+
12+
# Detect the middle of the array:
13+
my $mid = int( ( $low + $high ) / 2 );
14+
my $guess = $list[$mid];
15+
16+
# We found it out:
17+
if ( $guess == $item ) {
18+
return $mid;
19+
}
20+
21+
# The guess is too high, decrease it:
22+
elsif ( $guess > $item ) {
23+
$high = --$mid;
24+
}
25+
26+
# The guess is too low, increase it:
27+
else {
28+
$low = ++$mid;
29+
}
30+
}
31+
32+
# Nothing at all found:
33+
return 'None';
34+
35+
}
36+
37+
my @my_list = qw /1 3 5 7 9/;
38+
39+
# Should display "1":
40+
print binary_search( 3, @my_list ), "\n";
41+
42+
# Should display "None":
43+
print binary_search( -1, @my_list ), "\n";
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Detect the smallest value in an array
2+
sub findSmallest {
3+
4+
my @arr = @_;
5+
6+
my $smallest = $arr[0]; # Keep the smallest value
7+
my $smallest_index = 0; # Keep the index of the smallest value
8+
9+
for ( my $i = 1; $i <= $#arr; $i++ ) {
10+
$smallest_index = $i if $arr[$i] < $smallest;
11+
}
12+
13+
return $smallest_index;
14+
}
15+
16+
# Sort array
17+
sub selectionSort {
18+
19+
my @arr = @_;
20+
21+
my @newArr = ();
22+
23+
for ( 0 .. $#arr ) {
24+
my $smallest_index = findSmallest(@arr); # Find the smallest element in the array
25+
push @newArr, $arr[$smallest_index]; # Add it to the new array
26+
splice( @arr, $smallest_index, 1 ); # Delete that element
27+
}
28+
29+
return @newArr;
30+
}
31+
32+
print join( ' ', selectionSort( 5, 3, 6, 2, 10 ) ), "\n";

0 commit comments

Comments
 (0)