using System;

namespace Sort
{
    
/// <summary>
    
/// ============== Program Description==============
    
///Name:HeapSort.cs 
    
///Objective:Heap Sort 
    
///Date:2006-01-10 */
    
///Written By coffee.liu 
    
///================================================
    
/// </summary>

    class Sort
    
{
        
/// <summary>
        
/// 应用程序的主入口点。
        
/// </summary>

        [STAThread]
        
static void Main(string[] args)
        
{
            
int i;
            
int[] list={0,12,10,6,9,15,19,7,2,5,17,18,24,23,22,11,23,25,31,1};
            Console.WriteLine( 
"\nSorting values:" );
            
for ( i = 1 ; i < 20; i++ )
                Console.WriteLine( 
" List1 Number :{0} " , list[i] );
            Heap_Sort( list , 1
9 );

            Console.WriteLine( 
"\nSorting result:" );
            
for ( i = 1 ; i < 20; i++ )
                Console.WriteLine( 
" List2 Number :{0}" , list[i] );
            
            
        }

        
public static void Heap_Sort( int[] list , int index )
        
{
            
int i ;
            
int tmp ;

            
for ( i = ( index / 2 ) ; i >= 1 ; i -- )
                Create_Heap( list , i , index );

            
for ( i = index - 1 ; i >= 1 ; i -- )
            
{
                tmp 
= list[i+1];
                list[i
+1= list[1];
                list[
1= tmp;

                Create_Heap( list , 
1 , i );
            }

        }


        
private  static void Create_Heap( int[] array , int root , int index )
        
{
            
int  j ;
            
int tmp;
            
int finish;

            j 
= 2 * root ;
            tmp 
= array[root];
            finish 
= 0 ;

            
while ( j <= index && finish == 0 )
            
{
                
if ( j < index )
                    
if ( array[j] < array[j+1] )
                        j 
++;

                
if( tmp >= array[j] )
                
{
                    finish 
= 1;
                }

                
else
                
{
                    array[j
/2= array[j];
                    j 
= 2 * j;
                }

            }

            array[j
/2= tmp;
        }


    }

}

这是一个堆排序的简单实现,当然可以做的更复杂一些
我们甚至可以把它做成Simple Factory Pattem
以便以后扩展和升级

posted on 2006-04-20 16:07  coffeeliu  阅读(345)  评论(0编辑  收藏  举报