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

Here, we are going to learn how to sort an array in descending order using selection sort in Scala programming language?
Submitted by Nidhi, on May 09, 2021 [Last updated : March 10, 2023]

Scala – Sorting Array in Descending Order using Selection Sort

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

Scala code to sort an array in descending order using selection sort

The source code to sort an array in descending order using selection sort is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to sort an array in descending order 
// using selection sort

object Sample {  
    def main(args: Array[String]) {  
        var IntArray = Array(11,15,12,14,13)
        var i:Int=0
        var j:Int=0
        var t:Int=0
        
        var max:Int=0
        
        //Sort array in descending order using selection sort.
        while(i<5)
        {
            max=i;
            
            j=i+1
            while(j<5)
            {
                if(IntArray(j)>IntArray(max))
                    max=j;
                j=j+1;
            }
            
            t=IntArray(i);
            IntArray(i)=IntArray(max);
            IntArray(max)=t;
            
            i=i+1;
        }
        
        i=0;
        println("Sorted Array in descending order: ");
        while(i<5)
        {
            printf("%d ",IntArray(i));
            i=i+1;
        }
        println()
    }
}

Output

Sorted Array in descending order: 
15 14 13 12 11 

Explanation

In the above program, we used an object-oriented approach to create the program. We created an object Sample, and we defined main() function. The main() function is the entry point for the program.

In the main() function, we created an array IntArray that contains 5 integer items. Then we sorted the created array in descending order using selection sort. After that, we printed the sorted array on the console screen.

Scala Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.