Q:

Ruby program to sort an array in descending order using selection sort

belongs to collection: Ruby Arrays Programs

0

In this program, we will create an array of integers and then we will sort the created array in descending order using selection sort.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to sort an array in descending order using selection sort is given below. The given program is compiled and executed successfully.

# Ruby program to sort an array in descending order 
# using selection sort

arr = [12,39,49,87,68];

i=0;
j=0;
t=0;
max=0;

while(i<5)
    max=i;
    j=i + 1
    while(j<5)
        if(arr[j]>arr[max])
            max=j;
        end
        j=j + 1;
    end
    
    t=arr[i];
    arr[i]=arr[max];
    arr[max]=t;
    
    i=i + 1;
end

i=0;
print "Sorted Array in descending order: \n";
while(i<5)
    print arr[i]," ";
    i=i+1;
end

Output:

Sorted Array in descending order: 
87 68 49 39 12 

Explanation:

In the above program, we created an array of integer elements. Then we sorted the array elements in descending order using the selection sort mechanism. After that, we printed the sorted array.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Ruby Arrays Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Ruby program to sort an array in ascending order u... >>
<< Ruby program to sort an array in ascending order u...