希尔排序(C#数据结构学习八)

 

using System;
using System.Collections.Generic;
using System.Text;

namespace SoloDataStructure
{
    
class MyShellSort
    
{
          
/// <summary>
          
/// 希尔排序
          
/// </summary>
          
/// <param name="arr">需要排序的数列</param>

       static  void ShellSort (int[] arr)
         
{
             
int temp; //
             int n = arr.Length;
             
int gap = n / 2//初始步长
             while (gap != 0)
             
{
                 
for (int i = gap; i < arr.Length; i++)
                 
{
                     
int j;
                     temp
=arr[i];
                     
for (j = i; j >= gap; j = j - gap)  //同子序列的插入排序
                     {
                         
if (temp < arr[j - gap])
                             arr[j] 
= arr[j - gap]; //如果后面的小于前面的,交换位置
                         else
                             
break;
                     }

                         arr[j] 
= temp;            //插入      
                 }

                     gap 
/= 2//缩短步长
             }


         }
            
        
static void Main(string[] args)
        
{
    
            
int[] arr = new int[] 99,198,97,96,905,44,93,2,91};
            Console.Write(
"希尔排序前:");
            
for (int i = 0; i < arr.Length; i++)
                Console.Write(arr[i] 
+ ".");
            ShellSort(arr);
            Console.Write(
"\n希尔排序后:");
            
for (int i = 0; i < arr.Length; i++)
                Console.Write(arr[i]
+".");
             
            Console.ReadLine();
        }

    }

}

posted on 2007-01-01 20:40  Haozes  阅读(955)  评论(0编辑  收藏  举报