title: Selection Sort from both ends with Min and Max
body: <p>I was wondering why this code is not outputting the correct sequence of numbers (ascending). It has been taken from this material - <a href="http://www.enggjournals.com/ijcse/doc/IJCSE11-03-04-115.pdf" rel="noreferrer">Upgraded Selection Sort</a>. For example as I insert in array values like these - [8,5,6,1,4,7,3,0,2,9] it returns - [0,1,3,4,5,7,8,6,2,9].</p>
  
  <pre><code>#include&lt;iostream&gt;
  using namespace std;
  
  void Swap(int Arr[100],int Temp_min,int Temp_max)
  {
      int temp;
      temp = Arr[Temp_min];
      Arr[Temp_min] = Arr[Temp_max];
      Arr[Temp_max] =temp;
  }
  
  void OptimizedSelectSort(int Arr[],int n)
  {
      int i,j,min,max;
  
      for(i=0;i&lt;n/2;i++)
      {
          min = i;
          max = i;
          for(j=i+1;j&lt;n-i;j++)
          {
              if (Arr[j]&gt; Arr[max])
              {
                  max = j;
              }
              else if (Arr[j]&lt; Arr[min])
              {
                  min = j;
              }
          }
          if (i == max &amp;&amp; n-1-i == min)
          {
              Swap(Arr,min,max);
          }
          else
          {
              if ((min == n-1-i) &amp;&amp; (max != i))
              {
                  Swap(Arr,i,min);
                  Swap(Arr,n-1-i,max);
              }
              else if ((max == i) &amp;&amp; (min != n-1-i))
              {
                  Swap(Arr,n-1-i,max);
                  Swap(Arr,i,min);
              }
              else
              {
                  if(min != i)
                  {
                      Swap(Arr,i,min);
                  }
                  else if(max!= n-1-i)
                  {
                      Swap(Arr,max,n-1-i);
                  }
              }
          }
      }
  }
  
  int main()
  {
      int n;
      cout&lt;&lt;"Enter the size of array"&lt;&lt;endl;
      cin&gt;&gt;n;
      int * Mas;
      Mas = new int [n];
      int i;
      cout&lt;&lt;"Enter the elements"&lt;&lt;endl;
      for(i=0;i&lt;n;i++)
      {
          cin&gt;&gt;Mas[i];
      }
      OptimizedSelectSort(Mas, n);
      cout&lt;&lt;"Sakartots saraksts:";
  
      for(i=0;i&lt;n;i++)
      {
          cout&lt;&lt;Mas[i]&lt;&lt;" ";
      }
  }
  </code></pre>