BinarySearch

From: Roger Mason <rmason_at_esd.mun.ca>
Date: Thu, 23 Jul 2009 08:12:20 -0230


Hello,

I'd like to use TMath::BinarySearch to find the index of a value in an array. I have the following code:

#include <TGraph.h>
#include <TMath.h>
#include <iostream>

void bs () {
  // This is the whole spectrum
  TGraph* file1 = new TGraph("file1_2col_np.dat");

  Long64_t N = file1->GetN();
  Double_t* x  = file1->GetX();
  Double_t* y = file1->GetY();
  Double_t xmax = TMath::MaxElement(N,x);
  Double_t xmin = TMath::MinElement(N,x);
  printf("Minimum wavenumber = %f\n",xmin);   printf("Maximum wavenumber = %f\n",xmax);

  Double_t target;

  target = xmin;
  Long64_t l = TMath::BinarySearch(N,x,target);   cout << target << " is at " << l << endl;

  target = 17000.0;
  l = TMath::BinarySearch(N,x,target);
  cout << target << " is at " << l << endl;

  for ( Long64_t i = 0; i < N; i++ ) {
    if ( x[i] == target )
      cout << "(Brute force) " << target << " is at " << i << endl;   }

}

The output is as follows:

minnie 090706 $ root -b -q bs.C

<snip>

ROOT 5.20/00 (trunk_at_24524, Oct 01 2008, 15:00:00 on linux)

<snip>

root [0]
Processing bs.C...
Minimum wavenumber = 13890.000000
Maximum wavenumber = 19440.000000
13890 is at -1
17000 is at 5550
(Brute force) 17000 is at 2440

Will someone please tell me how to make BinarySearch work?

Thanks,
Roger Received on Thu Jul 23 2009 - 13:00:59 CEST

This archive was generated by hypermail 2.2.0 : Thu Jul 23 2009 - 17:50:01 CEST