Binary search and selection sort in Perl

* Create 01_binary_search.pl

* Typo fixed in 01_binary_search.pl

* Create 01_selection_sort.pl
This commit is contained in:
biosta
2018-04-20 18:21:28 +03:00
committed by Aditya Bhargava
parent ea74644c95
commit f24b9a6e35
2 changed files with 75 additions and 0 deletions

View File

@@ -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";