ADMB Documentation  11.5.3197
 All Classes Files Functions Variables Typedefs Friends Defines
dvsort.cpp
Go to the documentation of this file.
00001 /*
00002  * $Id$
00003  *
00004  * Copyright (c) 2009-2012 ADMB Foundation
00005  */
00011 #include <fvar.hpp>
00012 #include "qsort.h"
00013 
00017 void double_qsort(double *arr, unsigned n)
00018 {
00019   #define double_lt(a,b) ((*a)<(*b))
00020   QSORT(double, arr, n, double_lt);
00021 }
00022 
00026 void double_qsort2(double *arr, int *arr2, unsigned n)
00027 {
00028   #define double_lt(a,b) ((*a)<(*b))
00029   QSORT2(double, int, arr, arr2, n, double_lt);
00030 }
00031 
00040 dvector sort(const dvector & v, int NSTACK)
00041 {
00042    int lb=v.indexmin();
00043    int size=v.size();
00044 
00045    double *doublearray = new double[size];
00046    for(int i=0;i<size;i++)
00047    {
00048       doublearray[i] = v(lb+i);
00049    }
00050 
00051    if (size > 1)
00052    {
00053      double_qsort(doublearray, (unsigned int)size);
00054    }
00055 
00056    int ub=v.indexmax();
00057    dvector arr(lb, ub);
00058    for(int i=0;i<size;i++) {
00059       arr(lb+i) = doublearray[i];
00060    }
00061 
00062    delete [] doublearray;
00063    doublearray = 0;
00064 
00065    return arr;
00066 }
00067 
00077 dvector sort(const dvector &_v, const ivector &_index, int NSTACK)
00078 {
00079    ivector & index = (ivector &) _index;
00080    dvector & v = (dvector &) _v;
00081 
00082    if (v.size() != index.size())
00083    {
00084       cerr << " Incompatible array sizes in vector v and ivector index\n"
00085            << " in ivector sort(const ivector& v,const ivector& index)\n";
00086       ad_exit(1);
00087    }
00088 
00089    int lb=v.indexmin();
00090    int size=v.size();
00091 
00092    double *doublearray = new double[size];
00093    for(int i = 0;i < size; i++)
00094    {
00095       doublearray[i] = v(lb+i);
00096    }
00097 
00098    int *intarray = new int[size];
00099    for(int i=0;i<size;i++)
00100    {
00101       intarray[i] = lb + i;
00102    }
00103 
00104    if (size > 1)
00105    {
00106      double_qsort2(doublearray, intarray, (unsigned int)size);
00107    }
00108 
00109    int ub=v.indexmax();
00110    dvector arr(lb, ub);
00111    for(int i = 0;i < size; i++) {
00112       arr(lb+i) = doublearray[i];
00113    }
00114 
00115    for(int i = 0; i < size; i++) {
00116       index(index.indexmin()+i) = intarray[i];
00117    }
00118 
00119    delete[] doublearray;
00120    doublearray = 0;
00121 
00122    delete[] intarray;
00123    intarray = 0;
00124 
00125    return arr;
00126 }