Reputation: 58
I am creating a basic bubble sort and I don't understand why i am getting this error Use of uninitialized value in numeric lt (<) at line 10.
#!/usr/bin/perl -w
use strict;
use warnings;
my @nums = (7,3,5,8,5,2,3,5,7,3,5);
my $length = @nums;
for(my $i = 0; $i < $length; $i++){
for(my $j = 0; $j < $length; $j++){
if($nums[$j] lt $nums[$j+1]){
my $temp = $nums[$j];
$nums[$j] = $nums[$j+1];
$nums[$j+1] = $temp;
}
}
}
It seems to be having issues in the if comparison. I made sure that my array was properly initialized with these values and they are. If i print the values before the for loops they print fine and are initialized.
I assume I am just missing something very simple but I'm honestly lost.
Upvotes: 1
Views: 1444
Reputation: 57248
In your inner loop, $j
loops up to $length-1
. At that point, $nums[$j]
is the last element of the array. Then you compare it with $nums[$j+1]
which doesn't exist.
Upvotes: 1