diff --git a/01_introduction_to_algorithms/perl5/01_binary_search.pl b/01_introduction_to_algorithms/perl5/01_binary_search.pl new file mode 100644 index 0000000..5e47b2d --- /dev/null +++ b/01_introduction_to_algorithms/perl5/01_binary_search.pl @@ -0,0 +1,43 @@ +sub binary_search { + + my ( $item, @list ) = @_; + + # The borders inside where we are searching in: + my $low = 0; + my $high = $#list; + + # Do that until found or until just one element remains: + while ( $low <= $high ) { + + # Detect the middle of the array: + my $mid = int( ( $low + $high ) / 2 ); + my $guess = $list[$mid]; + + # We found it out: + if ( $guess == $item ) { + return $mid; + } + + # The guess is too high, decrease it: + elsif ( $guess > $item ) { + $high = --$mid; + } + + # The guess is too low, increase it: + else { + $low = ++$mid; + } + } + + # Nothing at all found: + return 'None'; + +} + +my @my_list = qw /1 3 5 7 9/; + +# Should display "1": +print binary_search( 3, @my_list ), "\n"; + +# Should display "None": +print binary_search( -1, @my_list ), "\n"; diff --git a/02_selection_sort/perl5/01_selection_sort.pl b/02_selection_sort/perl5/01_selection_sort.pl new file mode 100644 index 0000000..58c2a95 --- /dev/null +++ b/02_selection_sort/perl5/01_selection_sort.pl @@ -0,0 +1,32 @@ +# Detect the smallest value in an array +sub findSmallest { + + my @arr = @_; + + my $smallest = $arr[0]; # Keep the smallest value + my $smallest_index = 0; # Keep the index of the smallest value + + for ( my $i = 1; $i <= $#arr; $i++ ) { + $smallest_index = $i if $arr[$i] < $smallest; + } + + return $smallest_index; +} + +# Sort array +sub selectionSort { + + my @arr = @_; + + my @newArr = (); + + for ( 0 .. $#arr ) { + my $smallest_index = findSmallest(@arr); # Find the smallest element in the array + push @newArr, $arr[$smallest_index]; # Add it to the new array + splice( @arr, $smallest_index, 1 ); # Delete that element + } + + return @newArr; +} + +print join( ' ', selectionSort( 5, 3, 6, 2, 10 ) ), "\n";