bpmnr/nr_select.c

Go to the documentation of this file.
00001 
00005 #include <bpm/bpm_messages.h>
00006 #include <bpm/bpm_nr.h>
00007 
00014 double nr_select( int k, int n, double *org_arr ) {
00015 
00016   unsigned long i,ir,j,l,mid;
00017   double a,tempr;
00018   double *arr;
00019 
00020   if( ! org_arr ) {
00021     bpm_error( "Invalid array in nr_select(...)", 
00022                __FILE__, __LINE__ );
00023     return -DBL_MAX;
00024   }
00025 
00026   // First, create a copy of the array so this one doesn't get mashed up
00027   arr = malloc( (n+1) * sizeof(double) );
00028   memcpy( &(arr[1]), org_arr, n * sizeof(double) );
00029 
00030   // Now, perform the sort to find the selected element
00031   l=1;
00032   ir=n;
00033   for (;;) {
00034 
00035     if (ir <= l+1) {
00036       if (ir == l+1 && arr[ir] < arr[l]) {
00037         SWAP(arr[l],arr[ir]);
00038           }
00039       return arr[k];
00040     } else {
00041       mid=(l+ir) >> 1;
00042       SWAP(arr[mid],arr[l+1]);
00043         if (arr[l] > arr[ir]) {
00044           SWAP(arr[l],arr[ir]);
00045             }
00046       if (arr[l+1] > arr[ir]) {
00047         SWAP(arr[l+1],arr[ir]);
00048           }
00049       if (arr[l] > arr[l+1]) {
00050         SWAP(arr[l],arr[l+1]);
00051           }
00052       i=l+1;
00053       j=ir;
00054       a=arr[l+1];
00055       for (;;) {
00056         do i++; while (arr[i] < a);
00057         do j--; while (arr[j] > a);
00058         if (j < i) break;
00059         SWAP(arr[i],arr[j]);
00060       }
00061       arr[l+1]=arr[j];
00062       arr[j]=a;
00063       if (j >= k) ir=j-1;
00064       if (j <= k) l=i;
00065     }
00066   }
00067 
00068   return 0;
00069 }
00070 
00071              

Generated on Thu Jan 10 10:18:04 2008 for libbpm by  doxygen 1.5.1