Shalvin Interests

Thursday, September 15, 2011

Selection Sort in C#

using System;

public class SelectionSort
{
   private int[] data; 
   private static Random generator = new Random();

   public SelectionSort( int size )
   {
      data = new int[ size ]; 

       for ( int i = 0; i < size; i++ )
         data[ i ] = generator.Next( 10, 100 );
   } 

    public void Sort()
   {
      int smallest; 

      for ( int i = 0; i < data.Length - 1; i++ )
      {
         smallest = i; 

         // loop to find index of smallest element
         for ( int index = i + 1; index < data.Length; index++ )
            if ( data[ index ] < data[ smallest ] )
               smallest = index;

         Swap( i, smallest ); // swap smallest element into position
         PrintPass( i + 1, smallest ); // output pass of algorithm
      } 
   } 

    public void Swap( int first, int second )
   {
      int temporary = data[ first ]; 
      data[ first ] = data[ second ]; 
      data[ second ] = temporary; 
   } 
 
   public void PrintPass( int pass, int index )
   {
      Console.Write( "after pass {0}: ", pass );

      // output elements through the selected item
      for ( int i = 0; i < index; i++ )
         Console.Write( data[ i ] + "  " );

      Console.Write( data[ index ] + "* " ); // indicate swap

      // finish outputting array
      for ( int i = index + 1; i < data.Length; i++ )
         Console.Write( data[ i ] + "  " );
     
      Console.Write( "\n              " ); // for alignment

      // indicate amount of array that is sorted
      for( int j = 0; j < pass; j++ )
         Console.Write( "--  " );
      Console.WriteLine( "\n" ); // skip a line in output
   } 

   public override string ToString()
   {
      string temporary = "";

      foreach ( int element in data )
         temporary += element + "  ";

      temporary += "\n"; 
      return temporary;
   } 
} 



using System;

public class SelectionSortTest
{
   public static void Main( string[] args )
   {
      SelectionSort sortArray = new SelectionSort( 10 );
      
      Console.WriteLine( "Unsorted array:" );
      Console.WriteLine( sortArray ); 

      sortArray.Sort(); 

      Console.WriteLine( "Sorted array:" );
      Console.WriteLine( sortArray ); 
      Console.ReadLine();
   } 
} 

No comments:

Post a Comment