* X more docs for C
[mascara-docs.git] / C / sorting.and.searching.cormen.algo / src / ins.txt
blob67fdb38315e777e5540994fe5b0a456c2c6356d0
1 /* insert sort */
3 #include <stdio.h>
4 #include <stdlib.h>
6 typedef int T;          /* type of item to be sorted */
7 typedef int tblIndex;   /* type of subscript */
9 #define compGT(a,b) (a > b)
11 void insertSort(T *a, tblIndex lb, tblIndex ub) {
12     T t;
13     tblIndex i, j;
15    /**************************
16     *  sort array a[lb..ub]  *
17     **************************/
18     for (i = lb + 1; i <= ub; i++) {
19         t = a[i];
21         /* Shift elements down until */
22         /* insertion point found.    */
23         for (j = i-1; j >= lb && compGT(a[j], t); j--)
24             a[j+1] = a[j];
26         /* insert */
27         a[j+1] = t;
28     }
31 void fill(T *a, tblIndex lb, tblIndex ub) {
32     tblIndex i;
33     srand(1);
34     for (i = lb; i <= ub; i++) a[i] = rand();
37 int main(int argc, char *argv[]) {
38     tblIndex maxnum, lb, ub;
39     T *a;
41     /* command-line:
42      *
43      *   ins maxnum
44      *
45      *   ins 2000
46      *       sorts 2000 records
47      *
48      */
50     maxnum = atoi(argv[1]);
51     lb = 0; ub = maxnum - 1;
52     if ((a = malloc(maxnum * sizeof(T))) == 0) {
53         fprintf (stderr, "insufficient memory (a)\n");
54         exit(1);
55     }
57     fill(a, lb, ub);
58     insertSort(a, lb, ub);
60     return 0;