F# Program to Implement Selection Sort

F# Program to Implement Selection Sort

Sorting is a very important part of programming because it helps us arrange data in a clear and useful order. When numbers, names, or records are sorted, they become easier to read and faster to search. One simple and classic sorting method that beginners often learn is Selection Sort. It is not the fastest algorithm, but it is very easy to understand, which makes it a great starting point.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Selection Sort works by finding the smallest value from a group of data and placing it at the correct position. Then it repeats the same idea for the rest of the data until everything is sorted. In this article, we will explore how to write an F# program to implement Selection Sort in different ways. Each example uses simple ideas so beginners can learn step by step without feeling confused.

Program 1: Selection Sort Using Basic Loops

This program uses simple loops and a mutable array to perform Selection Sort. It follows the traditional method that many beginners see first when learning sorting.

open System

[<EntryPoint>]
let main argv =

    let numbers = [| 64; 25; 12; 22; 11 |]
    let n = numbers.Length

    for i in 0 .. n - 2 do

        let mutable minIndex = i

        for j in i + 1 .. n - 1 do

            if numbers.[j] < numbers.[minIndex] then
                minIndex <- j

        let temp = numbers.[minIndex]
        numbers.[minIndex] <- numbers.[i]
        numbers.[i] <- temp

    printfn "Sorted array:"
    numbers |> Array.iter (printf "%d ")

    0

This program works by selecting the smallest value in the remaining part of the array and swapping it with the current position. It is useful because the logic is clear and easy to trace. Beginners can understand how Selection Sort slowly builds a sorted section at the beginning of the array.

Program 2: Selection Sort Using Recursion

This program shows how Selection Sort can be written using recursion instead of loops. It introduces a more functional way of thinking in F#.

open System

let rec selectionSort (arr:int[]) start =

    if start >= arr.Length - 1 then arr
    else

        let mutable minIndex = start

        for i in start + 1 .. arr.Length - 1 do

            if arr.[i] < arr.[minIndex] then
                minIndex <- i

        let temp = arr.[start]
        arr.[start] <- arr.[minIndex]
        arr.[minIndex] <- temp

        selectionSort arr (start + 1)


[<EntryPoint>]
let main argv =

    let numbers = [| 29; 10; 14; 37; 13 |]
    selectionSort numbers 0 |> ignore

    printfn "Sorted array:"
    numbers |> Array.iter (printf "%d ")

    0

Here, recursion replaces the outer loop by calling the function again with the next position. This approach is helpful for beginners who want to learn how problems can be solved step by step using function calls. It also shows that Selection Sort logic stays the same even when the style changes.

Program 3: Selection Sort with Immutable Lists

This program uses immutable lists instead of arrays. It fits well with the functional nature of F# and avoids changing data directly.

open System

let selectionSort list =

    let rec sort remaining sorted =

        match remaining with
        | [] -> sorted
        | _ ->
            let minValue = List.min remaining
            let newRemaining = remaining |> List.filter ((<>) minValue)

            sort newRemaining (sorted @ [minValue])

    sort list []


[<EntryPoint>]
let main argv =

    let numbers = [64; 25; 12; 22; 11]
    let result = selectionSort numbers

    printfn "Sorted list:"
    result |> List.iter (printf "%d ")

    0

This version works by finding the smallest value and building a new sorted list. It is useful for understanding how Selection Sort can work without mutable data. Beginners can learn how functional programming encourages safer and cleaner code.

Program 4: Selection Sort with Index Tracking

This program adds clarity by separating the logic of finding the minimum index. It keeps the code readable while showing a slightly different structure.

open System

let findMinIndex (arr:int[]) start =

    let mutable minIndex = start

    for i in start + 1 .. arr.Length - 1 do

        if arr.[i] < arr.[minIndex] then
            minIndex <- i

    minIndex


[<EntryPoint>]
let main argv =

    let numbers = [| 20; 5; 16; 8; 2 |]
    let n = numbers.Length

    for i in 0 .. n - 2 do

        let minIndex = findMinIndex numbers i
        let temp = numbers.[i]
        numbers.[i] <- numbers.[minIndex]
        numbers.[minIndex] <- temp

    printfn "Sorted array:"
    numbers |> Array.iter (printf "%d ")

    0

This approach is helpful because it breaks the problem into smaller parts. Beginners can clearly see how the minimum value is found and then swapped. This makes the program easier to read and debug.

Program 5: Generic Selection Sort in F

This program shows how Selection Sort can work with any comparable type. It introduces generic programming in a gentle way.

open System

let selectionSortGeneric (arr:'a[]) =

    let n = arr.Length

    for i in 0 .. n - 2 do

        let mutable minIndex = i

        for j in i + 1 .. n - 1 do

            if arr.[j] < arr.[minIndex] then
                minIndex <- j

        let temp = arr.[i]
        arr.[i] <- arr.[minIndex]
        arr.[minIndex] <- temp

    arr


[<EntryPoint>]
let main argv =

    let numbers = [| 15; 3; 9; 6; 1 |]
    let sorted = selectionSortGeneric numbers

    printfn "Sorted array:"
    sorted |> Array.iter (printf "%d ")

    0

This version is useful because it shows how one Selection Sort function can be reused. Beginners can see how F# supports flexible and reusable code while keeping things simple.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Selection Sort and F# in a clear and friendly way.

Q1. What is Selection Sort mainly used for?
Selection Sort is mostly used for learning purposes. It helps beginners understand how sorting works step by step.

Q2. Is Selection Sort better than Bubble Sort?
Selection Sort usually performs fewer swaps than Bubble Sort, but both are slow for large data. They are mainly used for learning.

Q3. Why learn Selection Sort in F#?
Learning Selection Sort in F# helps beginners practice both sorting logic and functional programming ideas together.

Q4. Can Selection Sort be written without loops?
Yes, Selection Sort can be written using recursion or immutable lists, as shown in earlier examples.

Q5. Should beginners practice all versions?
Practicing different versions helps beginners understand the algorithm deeply and feel more confident with F#.

Conclusion

Selection Sort is a simple but powerful way to learn sorting algorithms. In this article, we explored many F# programs that implement Selection Sort using loops, recursion, immutable data, and generic functions. Each approach shows the same idea in a different style, making it easier for beginners to learn.

The best way to improve is to practice these programs, change the numbers, and run them again. With time and patience, sorting algorithms will feel natural, and learning more advanced topics in F# will become much easier and more enjoyable.

Scroll to Top