Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Selection sort in Perl (#5767)
Browse files Browse the repository at this point in the history
Co-authored-by: Riyazul555 <riyazulislam2003@gmail.com>
  • Loading branch information
Riyazul555 and MdRiyazulIslam authored Jul 1, 2024
1 parent e1bb7da commit da33008
Showing 1 changed file with 34 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/perl
use strict;
use warnings;

sub selection_sort {
my @list = @_;
my $n = scalar @list;

for my $i (0 .. $n - 2) {
# Set current element as minimum
my $min = $i;

# Check the element to be minimum
for my $j ($i + 1 .. $n - 1) {
if ($list[$j] < $list[$min]) {
$min = $j;
}
}

# Swap the minimum element with the current element
if ($min != $i) {
my $temp = $list[$i];
$list[$i] = $list[$min];
$list[$min] = $temp;
}
}

return @list;
}

# Example usage
my @unsorted_list = (64, 25, 12, 22, 11);
my @sorted_list = selection_sort(@unsorted_list);
print "Sorted list: @sorted_list\n";

0 comments on commit da33008

Please sign in to comment.