SelectionSort selection sort

SelectionSort selection sort

1 Algorithm steps

  1. First find the smallest (large) element in the unsorted sequence and store it at the beginning of the sorted sequence
  2. Then continue to find the smallest (large) element from the remaining unsorted elements, and then put it at the end of the sorted sequence.
  3. Repeat the second step until all elements are sorted.


Python code implementation

def selectionSort(arr):
    for i in range(len(arr)-1):
        # Record the minimum index
        minIndex = i
        for j in range(i + 1, len(arr)):
            if arr[j] <arr[minIndex]:
                minIndex = j
        # When i is not the smallest number, swap i and the smallest number
        if i != minIndex:
            arr[i], arr[minIndex] = arr[minIndex], arr[i]
    return arr

Go code implementation

func selectionSort(arr []int) []int {
    length := len(arr)
    for i := 0; i <length-1; i++ {
        min := i
        for j := i + 1; j <length; j++ {
            if arr[min]> arr[j] {
                min = j
        arr[i], arr[min] = arr[min], arr[i]
    return arr

Java code implementation

 public static int [] selectSort(int[] sourceArray) throws Exception{
        int[] arr = Arrays.copyOf(sourceArray,sourceArray.length);
       //A total of N-1 rounds of comparison are required
        for (int i=0;i<arr.length-1;i++){
            int min = i;
           //Each round needs to compare the following elements
            for(int j = i+1;j<arr.length;j++){
                if (arr[min]>arr[j])
                    min = j;
           //Exchange the minimum value found with the current coordinates
            if (i!=min){
                int tmp = arr[i];
                arr[i] = arr[min];
                arr[min] = tmp;
        return arr;
Reference: SelectionSort Selection Sort-Cloud + Community-Tencent Cloud