Task: Quickselect algorithm



C#: 





using System;
using System.Collections.Generic;
using System.Linq;

namespace QuickSelect
{
    internal static class Program
    {
        #region Static Members

        private static void Main()
        {
            var inputArray = new[] {9, 8, 7, 6, 5, 0, 1, 2, 3, 4};
            
            Console.WriteLine( "Loop quick select 10 times." );
            for( var i = 0 ; i < 10 ; i++ )
            {
                Console.Write( inputArray.NthSmallestElement( i ) );
                if( i < 9 )
                    Console.Write( ", " );
            }
            Console.WriteLine();

            
            
            Console.WriteLine( "Just sort 10 elements." );
            Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 10 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );
            
            Console.WriteLine( "Get 4 smallest and sort them." );
            Console.WriteLine( string.Join( ", ", inputArray.TakeSmallest( 4 ).OrderBy( v => v ).Select( v => v.ToString() ).ToArray() ) );
            Console.WriteLine( "< Press any key >" );
            Console.ReadKey();
        }

        #endregion
    }

    internal static class ArrayExtension
    {
        #region Static Members

        
        
        
        
        
        
        
        public static IEnumerable<T> TakeSmallest<T>( this T[] array, int count ) where T : IComparable<T>
        {
            if( count < 0 )
                throw new ArgumentOutOfRangeException( "count", "Count is smaller than 0." );
            if( count == 0 )
                return new T[0];
            if( array.Length <= count )
                return array;

            return QuickSelectSmallest( array, count - 1 ).Take( count );
        }

        
        
        
        
        
        
        
        public static T NthSmallestElement<T>( this T[] array, int n ) where T : IComparable<T>
        {
            if( n < 0 || n > array.Length - 1 )
                throw new ArgumentOutOfRangeException( "n", n, string.Format( "n should be between 0 and {0} it was {1}.", array.Length - 1, n ) );
            if( array.Length == 0 )
                throw new ArgumentException( "Array is empty.", "array" );
            if( array.Length == 1 )
                return array[ 0 ];

            return QuickSelectSmallest( array, n )[ n ];
        }

        
        
        
        
        
        
        
        private static T[] QuickSelectSmallest<T>( T[] input, int n ) where T : IComparable<T>
        {
            
            
            var partiallySortedArray = (T[]) input.Clone();
           
            
            var startIndex = 0;
            var endIndex = input.Length - 1;
            
            
            
            var pivotIndex = n;

            
            var r = new Random();
            while( endIndex > startIndex )
            {
                pivotIndex = QuickSelectPartition( partiallySortedArray, startIndex, endIndex, pivotIndex );
                if( pivotIndex == n )
                    
                    break;
                if( pivotIndex > n )
                    
                    endIndex = pivotIndex - 1;
                else                    
                    
                    startIndex = pivotIndex + 1;

                
                
                pivotIndex = r.Next( startIndex,  endIndex );
            }
            return partiallySortedArray;
        }

        
        
        
        
        
        
        
        
        
        
        
        
        private static int QuickSelectPartition<T>( this T[] array, int startIndex, int endIndex, int pivotIndex ) where T : IComparable<T>
        {
            var pivotValue = array[ pivotIndex ];
            
            array.Swap( pivotIndex, endIndex );
            for( var i = startIndex ; i < endIndex ; i++ )
            {
                if( array[ i ].CompareTo( pivotValue ) > 0 )
                    continue;

                
                array.Swap( i, startIndex );
                
                startIndex++;
            }
            
            array.Swap( endIndex, startIndex );
            return startIndex;
        }

        private static void Swap<T>( this T[] array, int index1, int index2 )
        {
            if( index1 == index2 )
                return;

            var temp = array[ index1 ];
            array[ index1 ] = array[ index2 ];
            array[ index2 ] = temp;
        }

        #endregion
    }
}








Fortran:       INTEGER FUNCTION FINDELEMENT(K,A,N)	
Chase an order statistic: FindElement(N/2,A,N) leads to the median, with some odd/even caution.
Careful
Charles Anthony Richard Hoare devised this method, as related to his famous QuickSort.
       INTEGER K,N		
       INTEGER A(N),HOPE,PESTY	
       INTEGER L,R,L2,R2	
        L = 1			
        R = N			
        DO WHILE (L .LT. R)	
          HOPE = A(K)		
          L2 = L		
          R2 = R		
          DO WHILE (L2 .LE. R2)	
            DO WHILE (A(L2) .LT. HOPE)	
              L2 = L2 + 1		
            END DO			
            DO WHILE (HOPE .LT. A(R2))	
              R2 = R2 - 1		
            END DO			
            IF (L2 - R2) 1,2,3	
    1       PESTY = A(L2)		
            A(L2) = A(R2)		
            A(R2) = PESTY		
    2       L2 = L2 + 1		
            R2 = R2 - 1		
    3     END DO		
          IF (R2 .LT. K) L = L2	
          IF (K .LT. L2) R = R2	
        END DO			
        FINDELEMENT = A(K)	
      END FUNCTION FINDELEMENT	

      PROGRAM POKE
      INTEGER FINDELEMENT	
      INTEGER N			
      PARAMETER (N = 10)	
      INTEGER A(66)		
      DATA A(1:N)/9, 8, 7, 6, 5, 0, 1, 2, 3, 4/	

      WRITE (6,1) A(1:N)	
    1 FORMAT ("Selection of the i'th element in order from an array.",/
     1 "The array need not be in order, and may be reordered.",/
     2 "  i Val:Array elements...",/,8X,666I2)

      DO I = 1,N	
        WRITE (6,2) I,FINDELEMENT(I,A,N),A(1:N)	
    2   FORMAT (I3,I4,":",666I2)	
      END DO		

      END