Advertisement
Guest User

Untitled

a guest
Oct 30th, 2016
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.14 KB | None | 0 0
  1. import std.stdio;
  2. import std.string;
  3. import std.file;
  4. import std.conv;
  5. import std.algorithm.iteration;
  6. import std.algorithm.sorting;
  7. import std.array;
  8. import std.functional;
  9.  
  10. alias toInt = compose!(to!int, stripLeft);
  11. alias readInts = compose!(array, map!toInt , lineSplitter ,chomp, readText);
  12.  
  13. T[] mergesort(T=int)(T[] arr) {    
  14.     T[] merge(T)(T[] a, T[]b) {
  15.         T[] result = new T[a.length + b.length];
  16.         auto frame = result[0..$];
  17.        
  18.         while ((a.length >0) && (b.length > 0)) {
  19.             if (a[0] < b[0]) {
  20.                 frame[0] = a[0];
  21.                 a = a[1..$];
  22.             }
  23.             else {
  24.                 frame[0] = b[0];
  25.                 b = b[1..$];
  26.             }
  27.             frame = frame[1..$];
  28.         }
  29.        
  30.         a ~= b;        
  31.         result[$-a.length..$] = a;
  32.        
  33.         return result;
  34.     }
  35.     return (arr.length < 2) ? arr : merge(mergesort(arr[0..$/2]), mergesort(arr[$/2..$]));
  36. }
  37.  
  38. int main(string[] args)
  39. {
  40.     int[] values = readInts(args[1]);
  41.     int[] sorted = mergesort(values);
  42.    
  43.     sort(values);
  44.    
  45.     return (values == sorted) ? 0 : -1;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement