Learn about the implementation of direct insertion sort and direct selection sort in C

  • 2020-05-09 18:58:16
  • OfStack

Direct insertion sort
Basic idea:
1. Starting with a[0], that is, starting with 1 element, is ordered; a[1]~a[n-1] is disordered.
2. Merge from a[1] into the previously ordered array until n-1.


#include <stdio.h> 
#define N 5 
 
void insertsort(int a[], int n); 
void swap(int *x, int *y); 
 
void insertsort(int a[], int n){ 
  int i,j; 
  for(i=1; i<n; i++){ 
    for(j=i; j>0 && a[j]<a[j-1]; j--){ 
      swap(&a[j], &a[j-1]); 
    }   
  } 
} 
 
void swap(int *x, int *y){ 
  int i = *x; 
  *x = *y; 
  *y = i; 
} 
 
int main(void){ 
  int a[N] = {2, 5, 3, 1, 8}; 
  insertsort(a, N); 
  int i; 
  for(i=0; i<N; i++) 
    printf("%d ", a[i]); 
  return 0; 
} 


Direct selection sort

Basic idea:
1. Find the subscript of the smallest number by comparison from 1. And then you swap the value of this index with 0.
2. Loop to 1, 2, 3... n - 1.


#include <stdio.h> 
#define N 5 
 
void selectsort(int a[], int n); 
void swap(int *x, int *y); 
 
void selectsort(int a[], int n){ 
  int i,j; 
  for(i=0; i<n; i++){ 
    int min = i; 
    for(j=i+1; j<n; j++){ 
      if(a[j] < a[min]){ 
        min = j; 
      } 
    } 
    swap(&a[i], &a[min]); 
  } 
} 
 
void swap(int *x, int *y){ 
  int i = *x; 
  *x = *y; 
  *y = i; 
} 
 
int main(void){ 
  int a[N] = {2, 5, 3, 1, 8}; 
  selectsort(a, N); 
  int i; 
  for(i=0; i<N; i++) 
    printf("%d ", a[i]); 
  return 0; 
} 



Related articles: