title: How to write the code for find the median of a variable in stata
body: <p>I am wondering how to write the codes for finding the median for a variable in stata without using <code>sort</code>, <code>egen</code>, <code>summarize</code>. This is what I got so far:</p>
  
  <pre><code>capture program drop find_median
  program find_median
      local n = _N
      gen ord=0
      forvalues i= 0/`n' {
          replace ord = `i' if [`1']&gt; [`1'][_n-1] &amp; [`1']&gt; [`1'][_n+1] 
      }
  end
  
  find_median (the variables...)
  </code></pre>