How to sort an array in descending order using selection sort with Swift

1 Answer

0 votes
import Foundation

func selectionSortDescending(_ array: inout [Int]) {
    let n = array.count
    
    for i in 0..<n-1 {
        var maxIndex = i
        for j in i+1..<n {
            if array[j] > array[maxIndex] {
                maxIndex = j
            }
        }
        if i != maxIndex {
            array.swapAt(i, maxIndex)
        }
    }
}

var numbers = [2, 141, 3, 4, 21, 13, 30, 50]

selectionSortDescending(&numbers)

print(numbers)  



/*
run:
     
[141, 50, 30, 21, 13, 4, 3, 2]
     
*/
 

 



answered Feb 26, 2025 by avibootz

Related questions

...