String Array Insertion Sort - C Data Structure

C examples for Data Structure:Sort

Description

String Array Insertion Sort

Demo Code

#include <stdio.h>
#include <string.h>

#define MaxNameSize 14//from   www.  jav  a2  s.co m
#define MaxNameBuffer MaxNameSize+1
#define MaxNames 8

void insertionSort3(int lo, int hi, int max, char list[MaxNames][MaxNameBuffer]) {
  char key[MaxNameSize];
  for (int i = lo + 1; i <= hi; i++) {
    strcpy_s(key, list[i]);
    int k = i - 1; //start comparing with previous item
    while (k >= lo && strcmp(key, list[k]) < 0) {
      strcpy_s(list[k + 1], list[k]);
      --k;
    }
    strcpy_s(list[k + 1], key);
  }
}

int main() {

  char name[MaxNames][MaxNameBuffer] = { "T", "D", "R", "S", "A","S", "K", "O" };

  insertionSort3(0, MaxNames - 1, MaxNameBuffer, name);

  for (int i = 0; i < MaxNames; i++)
    printf("%s\n", name[i]);
}

Related Tutorials