DEV Community

Cover image for selection sort algorithm
Kuldeep Singh
Kuldeep Singh

Posted on • Edited on • Originally published at programmingeeksclub.com

1

selection sort algorithm

Selection sort algorithm is a simple sorting algorithm. Selection sort algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.

The algorithm maintains two subarrays in a given array.

  • The subarray which already sorted.
  • The remaining subarray was unsorted.

Flowchart of selection sort algorithm

Image description

How it works?

  • Set minimum value(min_index) to location 0.
  • Traverse the array to find the minimum element in the array.
  • If any element smaller than (min_index) is found then swap both the values.
  • Increment (min_index) to point to the next element.
  • Repeat until the array is sorted.

Algorithm Implementation in Golang

package main

import (
    "fmt"
)

func selectionSort(arr []int) {
    var i, j, min_index int
    for i = 0; i < len(arr)-1; i++ {
        min_index = i
        for j = i + 1; j < len(arr); j++ {
            if arr[j] < arr[min_index] {
                min_index = j
            }
        }

        // if min_index is not equals to i then swap the indexes
        if min_index != i {
            arr[i], arr[min_index] = arr[min_index], arr[i]
        }
    }
}

func main() {
    arr := []int{12, 23, 34, 43, 4, 34, 24, 3, 53, 25454, 64}
    fmt.Println("before selection sort", arr)
    selectionSort(arr)
    fmt.Println("after selection sort", arr)
}
Enter fullscreen mode Exit fullscreen mode

If you find this article helpful you can also checkout my blog.

Programming Geeks Club

if anyone require any help please don't hesitate to leave comment.

Thanks for reading

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more