OneCompiler

Selection Sort in C

243

Selection Sort.png

SELECTION SORT

#include<stdio.h>

void selectionSort(int arr[],int n)
{
  
  int i,j,min_ind,temp;
  // One by one move boundary of unsorted subarray
  for (int i=0;i<n-1;i++)
  {
    // Find the minimum element in remaining unsorted array
    min_ind = i;
    for (int j=i+1;j<n;j++)
    {
      if (arr[j]<arr[min_ind])
      {
        min_ind = j;
      }
    }
    
    // Swap the found minimum element with the first element
    if (min_ind != i)
    {
      temp = arr[i];
      arr[i] = arr[min_ind];
      arr[min_ind] = temp;
    }
    
  }
}




void printArray(int *arr, int size)
{
  for (int i=0;i<size;i++)
  {
    printf("%d ",arr[i]);
  }
  printf("\n");
}


int main()
{
  int n;
  scanf("%d",&n);
  int arr[n];
  
  for(int i =0;i<n;i++){
    scanf("%d ",&arr[i]);
  }
  
  printArray(arr,n);
  
  selectionSort(arr,n);
  
  printArray(arr,n);
  
}