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

NAG CL Interface Introduction
Example description
/* nag_sort_search_vector (m01fsc) Example Program.
 *
 * Copyright 2024 Numerical Algorithms Group.
 *
 * Mark 30.1, 2024.
 */

#include <nag.h>
#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif
static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b);
#ifdef __cplusplus
}
#endif

int main(void) {
  Integer exit_status = 0;
  NagError fail;
  Pointer match;
  double key, *vec = 0;
  size_t i, n;

  INIT_FAIL(fail);

  /* Skip heading in data file */
  scanf("%*[^\n]");
  printf("nag_sort_search_vector (m01fsc) Example Program Results\n");
  /* Read number of points and number to search for */
  scanf("%" NAG_UFMT "%lf", &n, &key);
  if (n >= 1) {
    if (!(vec = NAG_ALLOC(50, double))) {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  } else {
    printf("Invalid n.\n");
    exit_status = 1;
    return exit_status;
  }
  for (i = 0; i < n; ++i)
    scanf("%lf", &vec[i]);
  /* nag_sort_search_vector (m01fsc).
   * Searches a vector for either the first or last match to a
   * given value
   */
  if (nag_sort_search_vector((Pointer)&key, (Pointer)vec, n,
                             (ptrdiff_t)(sizeof(double)), compare,
                             Nag_Ascending, Nag_First, &match, &fail)) {
    printf("Exact match found: ");
    if (fail.code != NE_NOERROR) {
      printf("Error from nag_sort_search_vector (m01fsc).\n%s\n", fail.message);
      exit_status = 1;
      goto END;
    }
    printf("First match index: %" NAG_UFMT "\n",
           (size_t)((double *)match - vec));
  } else {
    printf("No exact match found: ");
    if (match != NULL)
      printf("Nag_First nearest match index = %" NAG_UFMT "\n",
             (size_t)((double *)match - vec));
    else
      printf("No match in the input array\n");
  }
END:
  NAG_FREE(vec);
  return exit_status;
}

static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b) {
  double x = *((const double *)a);
  double y = *((const double *)b);
  return (x < y ? -1 : (x == y ? 0 : 1));
}