• Top Posts

    Sorting of an array of numbers


    • If an array containing number is sorted using sort function it takes every value in the array as a string so 12 will be placed before 2. 
    • Therefore, to consider the values as a number, spaceship operator() is used instead of cmp in the sort function. 
    • This operator considers its operands as a number and sorts the data as a number.


    # Initializing an array
    @n = (12, 44, 2, 5, 25, 7, 96, 1);
      
    # Printing Original Array
    print "Original Array: @n\n";
      
    # Sorting numbers with use of
    # spaceship operator
    @x = sort { $a <=> $b } @n;
      
    # Printing sorted array
    print "Array after Sorting: @x";

    Output:
    Original Array: 12 44 2 5 25 7 96 1
    Array after Sorting: 1 2 5 7 12 25 44 96

    No comments

    Post Top Ad

    ad728

    Post Bottom Ad

    ad728