Advertisement
zvoulgaris

Squares of a Sorted Array

Mar 6th, 2020
3,267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 0.99 KB | None | 0 0
  1. # Squares of a Sorted Array
  2.  
  3. function MergeSortedLists(x::Array{Int64, 1}, y::Array{Int64, 1})
  4.     nx = length(x)
  5.     ny = length(y)
  6.     n = nx + ny
  7.     z = Array{Int64}(undef, n)
  8.     c = 1
  9.     cx = 1
  10.     cy = 1
  11.  
  12.     if x[1] < y[1]
  13.         z[1] = x[1]
  14.         cx += 1
  15.     else
  16.         z[1] = y[1]
  17.         cy += 1
  18.     end
  19.  
  20.     while c < n
  21.         c += 1
  22.  
  23.         if x[cx] < y[cy]
  24.             z[c] = x[cx]
  25.             cx += 1
  26.  
  27.             if cx > nx
  28.                 c += 1
  29.                 z[c:end] = y[cy:end]
  30.                 c = n
  31.             end
  32.         else
  33.             z[c] = y[cy]
  34.             cy += 1
  35.  
  36.             if cy > ny
  37.                 c += 1
  38.                 z[c:end] = x[cx:end]
  39.                 c = n
  40.             end
  41.         end
  42.     end
  43.  
  44.     return z
  45. end
  46.  
  47. function main(z::Array{Int64, 1})
  48.     x = z[z.<0] # list of negative numbers
  49.     y = z[z.>=0] # list of positive numbers
  50.     x .^= 2
  51.     y .^= 2
  52.     return MergeSortedLists(reverse(x), y)
  53. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement