NAG Library Manual, Mark 30
Interfaces:  FL   CL   CPP   AD 

NAG CL Interface Introduction
Example description
/* nag_sort_intvec_search (m01nbc) Example Program.
 *
 * Copyright 2024 Numerical Algorithms Group.
 *
 * Mark 30.0, 2024.
 */
/* Pre-processor includes */
#include <math.h>
#include <nag.h>
#include <stdio.h>

int main(void) {
  /*Logical scalar and array declarations */
  Nag_Boolean validate;
  /*Integer scalar and array declarations */
  Integer exit_status = 0;
  Integer i, index, item, leniv, m1, m2;
  Integer *iv = 0;
  NagError fail;

  INIT_FAIL(fail);

  printf("%s\n", "nag_sort_intvec_search (m01nbc) Example Program Results");
  printf("\n");
  scanf("%*[^\n] ");
  scanf("%" NAG_IFMT "%*[^\n] ", &leniv);
  if (!(iv = NAG_ALLOC(leniv, Integer))) {
    printf("Allocation failure\n");
    exit_status = -1;
    goto END;
  }
  /* Read in Reference Vector iv */
  for (i = 0; i < leniv; i++)
    scanf("%" NAG_IFMT " ", &iv[i]);
  scanf("%*[^\n] ");
  /* Read items sought in the reference vector */
  validate = Nag_TRUE;
  m1 = 0;
  m2 = leniv - 1;
  while (scanf("%" NAG_IFMT "%*[^\n] ", &item) != EOF)
  {
    /*
     * nag_sort_intvec_search (m01nbc)
     * Binary search in set of integer numbers
     */
    index = nag_sort_intvec_search(validate, iv, m1, m2, item, &fail);
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_sort_intvec_search (m01nbc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
    if (validate) {
      /* Print the reference vector */
      printf("%s\n", "Reference Vector is:");
      for (i = 0; i < leniv; i++)
        printf("%5" NAG_IFMT "%s", iv[i], (i + 1) % 8 ? " " : "\n");
      printf("\n");
      validate = Nag_FALSE;
    }
    printf("\n");
    printf("  Search for item %5" NAG_IFMT " returned index: %4" NAG_IFMT "\n",
           item, index);
  }

END:
  NAG_FREE(iv);

  return exit_status;
}