Selection Sort in Go Lang

Go ProgrammingServer Side ProgrammingProgramming

Selection sort is a sorting algorithm that is used to sort the elements by repeatedly finding the minimum element and placing it at the first in the unsorted part of the array. After placing the minimum element in one end of the array, the array is then divided into two subparts which can be again sorted using the algorithm.

For Example

Input

arr[ ] = {2,9,4,3,5,1}

Output

1 2 3 4 5 9

Explanation

After sorting the given array, it becomes 1,2,3,4,5,9

Algorithm:

  • Take an array of integers as the input.
  • Find the index of the minimum element by iterating over the array.
  • If the number found is minimum, then swap with its previous element.
  • Now return the sorted array.

Example

Live Demo

package main
import "fmt"
func Selection_Sort(array[] int, size int) []int {
   var min_index int
   var temp int
   for i := 0; i < size - 1; i++ {
      min_index = i
      // Find index of minimum element
      for j := i + 1; j < size; j++ {
         if array[j] < array[min_index] {
            min_index = j
         }
      }
      temp = array[i]
      array[i] = array[min_index]
      array[min_index] = temp
   }
   return array
}
func main() {
   var num = 7
   array := []int{2,4,3,1,6,8,5}
   fmt.Println(Selection_Sort(array, num))
}

Running the above code will generate the output as,

Output

[1 2 3 4 5 6 8]

The given array is: [2, 4, 3, 1, 6, 8, 5]. After sorting the elements using Selection Sort, the array will become [1, 2, 3, 4, 5, 6, 8].

raja
Published on 23-Feb-2021 05:45:35
Advertisements