#!/usr/bin/perl # read the array from standard input one item at a time # then sort it , using the built in sort function and the # bubble sort function I wrote. You will probably never use # the bubble sort but it is nice to see the code. This was # used before the days when the sort command was invented. # # usage perlbubble # # You will then be prompted to one at a time enter the array # elements. print ("Enter the array to sort, one item at a time.\n"); print ("Enter an empty line to quit.\n"); $count = 1; $inputline = ; chop ($inputline); # As long as we do not have an empty line # read input line into array, increment count of # array elements, and remove linefeed at end of line before # entering it into array element # while ($inputline ne "") { @array[$count-1] = $inputline; $count += 1; $inputline = ; chop ($inputline); } # now sort the array, the easy way!! print (" Sort using built in sort command\n\n"); @array_result = sort (@array); print ("@array_result \n"); print ("\n\n Now sorting using Bubble Sort \n\n"); # Begin Bubble Sort Section # Start with first element of array, compare it to the next # element, if the second element is greater than the first, # do nothing else, switch them. Now compare the second and # third element, if the second is less than the third do # nothing else switch them. Keep doing this till you get to # the end of the array. Now you have done the first iteration. # After the first iteration you can be sure that the last element # in the array is done. It has bubbled up to the end. So in the # next iteration you go the array elements - 1. So in the simplest # case, for 3 elements there would be 2 iterations. # I have printed inbetween what is happening so you can see # how it works, as we move through the array one element at # a time. Note, this is not the most efficient sort. There are at # least 8 different kinds. I present this only as a teaching tool. # I have improved the efficiency by adding in a swapcount. That is # if there is no swapping for an iteration we are done! # $count = 1; print ("This is the original @array \n"); while ($count < @array) { $x = 1; $swapcount = 0; while ($x < @array) { if ($array[$x - 1] gt $array[$x]) { $swapcount++; @array[$x-1,$x] = @array[$x,$x-1]; } $x++; } if ($swapcount < 1 ) { print ("Finished sorting, leaving now! \n"); exit; } print ("After iteration number $count @array \n"); $count++; } exit;