Selection Sort

Introduction

Selection sort works by selecting the smallest value out of the unsorted part of the array and placing it at the back of the sorted part of the array.

Algorithm

  1. find the smallest number in the between index 0 and n-1

  2. swap it with the value at index 0

  3. repeat above 2 steps each time, starting at one index higher than previous and swapping into that position

Animation

C/C++ Implementation

void selectionSort(int arr[],int size){
    int i,j;
    int min;  //index of smallest value in the unsorted array

    for(int i=0;i<size-1;i++){
        min=i;
        for(int j=i+1;j<size;j++){
            if(arr[j] < arr[min]){
                min=j;
            }
        }
        if(min!=i){
            int tmp=arr[min];
            arr[min]=arr[i];
            arr[i]=tmp;
        }
    }
}

Last updated