7 September 2014

Quiz 20: Write a program for Quicksort

Problem:
Explain quicksort sort 

Input Format: 
unsorted array

Output Format: 
sorted array

Constraints: 
none

Sample Input
8 1 4 -2 6 3

Sample Output:
-2 1 3 4 6 8

Explanations:-
Quick Sort will select a pivot and rearrange elements to its right and left. Smaller numbers at left and larger at right. Then apply same logic to left and right elements. List will get sort automatically. 

Solution:

sub qsort {
    return if not @_;
    my $pivot = shift @_;
    return (
      qsort( grep { $_ <  $pivot }  @_ ), 
      $pivot,
      qsort( grep { $_ >= $pivot }  @_ ),
    );
}
@arr=(8, 1, 4, -2, 6, 3);
@ab = qsort(@arr);
print "@ab ";


Tips:
@_ store the arguments passed to subroutine in form of array

No comments:

Post a Comment