 
     // Note: keys have not been modified
     // Note: permutation now maps unsorted keys to sorted order
-    
+  
+    // permute the key arrays by the final permuation
+    apply_permutation(lower,  permutation);
+    apply_permutation(middle, permutation);
+    apply_permutation(upper,  permutation);
+
     std::cout << "Sorted Keys" << std::endl;
     for(size_t i = 0; i < N; i++)
     {
-        // p is the index in the *unsorted* arrays of the i-th sorted element
-        int p = permutation[i];
-        std::cout << "(" << upper[p] << "," << middle[p] << "," << lower[p] << ")" << std::endl;
+        std::cout << "(" << upper[i] << "," << middle[i] << "," << lower[i] << ")" << std::endl;
     }
 
     return 0;
 }
+

}


// random digit: integer in [0,10)
int rand10()
{
    return rand() % 10;
}



    size_t N = 20;

    // generate three arrays of random values
    thrust::device_vector<int> upper  = random_vector(N);
    thrust::device_vector<int> middle = random_vector(N);
    thrust::device_vector<int> lower  = random_vector(N);
    
    std::cout << "Unsorted Keys" << std::endl;
    for(size_t i = 0; i < N; i++)
