Implementation of insertion sort and direct selection sort in C basic sorting algorithm

  • 2020-05-30 20:35:09
  • OfStack

This paper illustrates the implementation of insertion sort and direct selection sort in C basic sorting algorithm. I will share it with you for your reference as follows:

Declares the type of element to be sorted


/*--------------------------
typedef.h
 Easy to modify the element type to be sorted 
-------------------------------------*/
#ifndef TYPEDEF_H
#define TYPEDEF_H
typedef int T;
#endif

Insertion sort:


/*---------------------------------------------------------------------------------------
Insertion_sort.h
 Direct insertion sort 
 Sort the elements given as an array 
 The time complexity is ( Reverse order number )N(N-1)/4 = O(N^2), And we're going to get to that in the worst case 
 At best N Second, worst-case run 2+3+ ... +N
------------------------------------------------------------------------------------------------*/
#ifndef INSERTION_SORT_H
#define INSERTION_SORT_H
#include "typedef.h"
// Direct insertion sort  
void Insertion_sort(T *a, int n)
{
  for(int i = 1; i != n; ++i)
  {
    T temp = a[i];
    int j = i - 1;
    for(; j >= 0 && temp < a[j]; --j )
      a[j + 1] = a[j];
    a[j + 1] = temp;
  }
}
#endif

Direct selection sort:


/*----------------------------------------------
DirectSelection_sort.h
 Direct selection sort 
 Time complexity O(N^2)
--------------------------------------------------------*/
#ifndef DIRECTSELECTION_SORT_H
#define DIRECTSELECTION_SORT_H
#include "typedef.h"
#include "swap.h"
// Sort by direct selection 
void DirectSelection_sort(T*a, int n)
{
  for(int i = 0; i != n; ++i)
  {
    int k = i;
    for(int j = i; j != n; ++j)
      if(a[j] < a[k]) k = j;
    swap(a[k],a[i]);
  }
}
#endif

I hope this article has been helpful to you in programming C.


Related articles: