Insertion Sort an Array - C Data Structure

C examples for Data Structure:Sort

Description

Insertion Sort an Array

Demo Code

#include <stdio.h>
#define MaxNumbers 10/*from   w  ww  .j  ava 2  s.c  om*/

void insertionSort(int [], int);

void insertionSort1(int [], int, int);

void insertionSort2(int [], int, int);


int main() {
    
    int num[] = {10, 3, 5, 4, 6, 8, 12, 7, 13, 17};
    
    int n = 10;

    insertionSort2(num, 0, n-1);

    for (int i = 0; i < n; i++) 
       printf("%d \n", num[i]);

}

void insertionSort(int list[], int n) {
    for (int i = 1; i < n; i++) {
        int key = list[i];
        int k = i - 1; //start comparing with previous item
        while (k >= 0 && key < list[k]) {
            list[k + 1] = list[k];
            --k;
        }
        list[k + 1] = key;
    }
}

void insertionSort1(int list[], int lo, int hi) {
    for (int i = lo + 1; i <= hi; i++) {
        int key = list[i];
        int k = i - 1; //start comparing with previous item
        while (k >= lo && key < list[k]) {
            list[k + 1] = list[k];
            --k;
        }
        list[k + 1] = key;
    }
}
void insertInPlace(int newItem, int list[], int m, int n) {
    int k = n;
    while (k >= m && newItem < list[k]) {
        list[k + 1] = list[k];
        --k;
    }
    list[k + 1] = newItem;
}

void insertionSort2(int list[], int lo, int hi) {
    void insertInPlace(int, int [], int, int);
    for (int i = lo + 1; i <= hi; i++)
        insertInPlace(list[i], list, lo, i - 1);
}

Related Tutorials