2016年2月7日 星期日

java-sort


source :

http://mathbits.com/MathBits/Java/arrays/SelectionSort.htm



Array at beginning: 846976869491
After Pass #1:849176869469
After Pass #2:849194867669
After Pass #3: 869194847669
After Pass #4: 949186847669
After Pass #5 (done): 949186847669

While being an easy sort to program, the selection sort is one of the least efficient.  The algorithm offers no way to end the sort early, even if it begins with an already sorted list.  

// Selection Sort Method for Descending Orderpublic static void SelectionSort ( int [ ] num )
{
     int i, j, first, temp; 
     for ( i = num.length - 1; i > 0; i - - ) 
     {
          first = 0;  
 //initialize to subscript of first element
          for(j = 1; j <= i; j ++)   
//locate smallest element between positions 1 and i.
          {
               if( num[ j ] < num[ first ] )         
                 first = j;
          }
          temp = num[ first ];   //swap smallest found with element in position i.
          num[ first ] = num[ i ];
          num[ i ] = temp;
      }          
}

 


沒有留言:

張貼留言