[prev] 35 [next]

Example: Insertion Sort in C (cont)

#include <stdio.h> // include standard I/O library defs and functions

#define SIZE 6     // define a symbolic constant

int main(void) {                                // main: program starts here
   int i;                                       // each variable must have a type
   int numbers[SIZE] = { 3, 6, 5, 2, 4, 1 };    /* array declaration
                                                   and initialisation */
   for (i = 1; i < SIZE; i++) {                 // for-loop syntax
      int element = numbers[i];                                                    
      int j = i-1;
      while (j >= 0 && numbers[j] > element) {  // logical AND
         numbers[j+1] = numbers[j];
         j--;                                   // abbreviated assignment j=j-1 
      }
      numbers[j+1] = element;                   // statements terminated by ;
   }                                            // code blocks enclosed in { } 

   for (i = 0; i < SIZE; i++)
      printf("%d\n", numbers[i]);               // printf defined in <stdio>

   return 0;             // return program status (here: no error) to environment
}