function [geneorder]=minimalneighbor(matrix,geneno,geneseries)
%matrix ---> Complete data similarity matrix with diagonals filled with
%           -9999 (ex: Complete Data Similarity Matrix of Yeast Complex)
%geneno ---> Total no of genes to be ordered
%geneseries--->Indexes (as in the complete similarity matrix) of the genes to be ordered in row format. 
%               May be genes within clusters, but gene index should be the
%               same as in complete similarity matrix
%               
%The ordering is calculated on the similarity matrix "matrix" (square).
% NOTE: A distanc matrix (e.g. obtained with Euclidean distance) can be turned into a similarity matrix , e.g. sim = 1-dist(data) and vice-versa;
if geneno==1
   geneorder=geneseries(geneno);
else
geneseries=geneseries(1:geneno);

%Calculation of the closest genes in the matrix (Step1) and keeping in array geneorder
%max=0;
[tow,index]=max(matrix(geneseries,geneseries));
   [al,col]=max(tow);
   row=index(col);
   geneorder(1)=geneseries(col);
   geneorder(2)=geneseries(row);
   
   %replacing ith and jth gene with 1st and 2nd one;
   matrix(geneseries,geneorder(1))=-9999;
   matrix(geneseries,geneorder(2))=-9999;

%Calculating the two nearest genes from the two end genes in "geneorder" (Step 2). They may be the same
   [tow,index]=max(matrix(geneorder(2),geneseries));
   [to,ind]=max(matrix(geneorder(1),geneseries));
end  
if geneno>2   
%Repeating Step 2 to form the complete gene order.
for k=3:geneno,
  
         %If both the selected genes are same, after connecting to array we have no selected genes remaining
         if index==ind            
             if to>(tow+.000001)
                geneorder=[geneseries(ind) geneorder];
             else
               geneorder(k)=geneseries(index);
            end 
            matrix(geneseries,geneseries(index))=-9999;
            % and we have to calculate twice to get selected genes to be used in next step.
            
            [tow,index]=max(matrix(geneorder(k),geneseries));    
            [to,ind]=max(matrix(geneorder(1),geneseries));
            
        %Otherwise we connect only one selected gene and the gene index of the other selected gene is stored      
        elseif to>(tow+.000001)
               geneorder=[geneseries(ind) geneorder];
               matrix(geneseries,geneseries(ind))=-9999;
              %As the index of one selected gene is stored we have to compute for the other nearest gene only.
              %In this computation the gene, whose index is stored, is also considered to be a candidate for connectioon
              %to the other end of the array "geneorder".
              [to,ind]=max(matrix(geneorder(1),geneseries));          
           else
              geneorder(k)=geneseries(index);
             matrix(geneseries,geneseries(index))=-9999;            
             [tow,index]=max(matrix(geneorder(k),geneseries));            
         end                 
        end
  end
     
