Advertisement
thornik

Bench 'Heapsort' for D

Dec 5th, 2017
2,082
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.19 KB | None | 0 0
  1. // ldc2.exe -release -m64 -O heapsort.d
  2.  
  3. import std.conv;
  4. import std.stdio;
  5.  
  6. const int IM = 139968;
  7. const int IA =   3877;
  8. const int IC =  29573;
  9.  
  10. double gen_random(double max)
  11. {
  12.     static int last = 42;
  13.     return max * (last = (last * IA + IC) % IM) / IM;
  14. }
  15.  
  16. void heapsort(int n, double[] ra) {
  17.     int i, j;
  18.     int ir = n;
  19.     int l = (n >> 1) + 1;
  20.     double rra;
  21.  
  22.     for (;;) {
  23.         if (l > 1) {
  24.             rra = ra[--l];
  25.         } else {
  26.             rra = ra[ir];
  27.             ra[ir] = ra[1];
  28.             if (--ir == 1) {
  29.                 ra[1] = rra;
  30.                 return;
  31.             }
  32.         }
  33.         i = l;
  34.         j = l << 1;
  35.         while (j <= ir) {
  36.             if (j < ir && ra[j] < ra[j+1])
  37.                 ++j;
  38.             if (rra < ra[j]) {
  39.                 ra[i] = ra[j];
  40.                 j += (i = j);
  41.             } else {
  42.                 j = ir + 1;
  43.             }
  44.         }
  45.         ra[i] = rra;
  46.     }
  47. }
  48.  
  49. void main(string[] args)
  50. {
  51.     int N = args.length < 2 ? 1 : to!int(args[1]);
  52.     auto ary = new double[N + 1];
  53.    
  54.     for (int i = 1; i <= N; i++)
  55.        ary[i] = gen_random(1);
  56.  
  57.     heapsort(N, ary);
  58.     writeln(ary[N]);
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement