// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>

using namespace std;

template<class T>
void qsix(int n1,int n2,T *a,int *ix)
{
   int l=n1;
   int r=n2;
   T pivot=a[ix[(n1+n2)/2]];
   do {
      while(a[ix[l]]<pivot) l++;
      while(a[ix[r]]>pivot) r--;
      if(l<=r) {
         int tmp=ix[l];
         ix[l]=ix[r];
         ix[r]=tmp;
         l++;
         r--;
      }
   } while(l<=r);
   if(n1<r) qsix(n1,r,a,ix);
   if(l<n2) qsix(l,n2,a,ix);
   return;
}

template<class T1,class T2>
void qs2(int n1,int n2,T1 *a,T2 *b)
{
   int l=n1;
   int r=n2;
   T1 pivot=a[(n1+n2)/2];
   do {
      while(a[l]<pivot) l++;
      while(a[r]>pivot) r--;
      if(l<=r) {
         T1 tmp1=a[l];
         a[l]=a[r];
         a[r]=tmp1;
         T2 tmp2=b[l];
         b[l]=b[r];
         b[r]=tmp2;
         l++;
         r--;
      }
   } while(l<=r);
   if(n1<r) qs2(n1,r,a,b);
   if(l<n2) qs2(l,n2,a,b);
   return;
}

const int N = 10;

int main()
{
    srand(time(NULL));
    int ia[N];
    string sa[N];
    char tmp[2];
    tmp[1] = '\0';
    for(int i=0;i<N;i++)
    {
        ia[i] = rand();
        tmp[0] = 'A' + i;
        sa[i] = tmp;
    }
    cout << "Usorteret:" << endl;
    for(int i=0;i<N;i++)
    {
        cout << ia[i] << " " << sa[i] << endl;
    }
    int ix[N];
    for(int i=0;i<N;i++) ix[i]=i;
    qsix<int>(0,N-1,ia,ix);
    cout << "Sorteret med index:" << endl;
    for(int i=0;i<N;i++)
    {
        cout << ia[ix[i]] << " " << sa[ix[i]] << endl;
    }
    qs2<int,string>(0,N-1,ia,sa);
    cout << "Sorteret med 2 arrays:" << endl;
    for(int i=0;i<N;i++)
    {
        cout << ia[i] << " " << sa[i] << endl;
    }
    return 0;
}
