3. Accepting series of numbers, strings from keyboard and sorting them ascending, descending order.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace lrn2CSharp3
{
class Program
{
static void Main( string[ ] args )
{
Console.Write( "Please enter the number of items you wish to enter: " );
int num_item = Convert.ToInt32( Console.ReadLine( ) );
int[ ] nums = new int[ num_item ];
for ( int i = 0; i < num_item; i++ )
{
Console.Write( "Item " + i + ": " );
nums[ i ] = Convert.ToInt32( Console.ReadLine( ) );
}
qsort( nums );
foreach ( int num in nums )
Console.Write( num.ToString( ) + " " );
Console.WriteLine( "" );
nums = reverse( nums );
foreach ( int num in nums )
Console.Write( num.ToString( ) + " " );
Console.WriteLine( "" );
Console.WriteLine( "Press esc to exit." );
while ( !keyPressHandler( Console.ReadKey( true ) ) )
{
Thread.Sleep( 250 );
/* no op */
}
}
static void swap<T>( ref T lhs, ref T rhs )
{
T temp;
temp = lhs;
lhs = rhs;
rhs = temp;
}
static void qsort( int[ ] nums )
{
qs( nums, 0, nums.Length - 1 );
}
static void qs( int[ ] items, int left, int right )
{
int i, j;
int x;
i = left;
j = right;
x = items[ ( left + right ) / 2 ];
do
{
while ( ( items[ i ] < x ) && ( i < right ) )
i++;
while ( ( x < items[ j ] ) && ( j > left ) )
j--;
if ( i <= j )
{
swap<int>( ref items[ i ], ref items[ j ] );
i++;
j--;
}
} while ( i <= j );
if ( left < j )
qs( items, left, j );
if ( i < right )
qs( items, i, right );
}
static int[ ] reverse( int[ ] items )
{
int[ ] reversed = new int[ items.Length ];
int j = 0;
for ( int i = items.Length - 1; i >= 0; i-- )
{
reversed[ j ] = items[ i ];
j++;
}
return reversed;
}
protected static Boolean keyPressHandler( ConsoleKeyInfo input )
{
if ( input.Key == ConsoleKey.Escape )
return true;
return false;
}
}
}
posted by dharh 1:40 AM Nov 29th, 2009