代码改变世界

排序算法‘冒泡排序,选择排序,快速排序’

2005-06-22 09:48  Jeffrey Lee  阅读(587)  评论(0编辑  收藏  举报

常用排序工具类:
SortClass 的摘要说明。
  对整形数组进行排序
  可以重写每个排序算法支持多类型
  注意:数组、对象,为传地址指针的形式
  执行方法后会便改原始数组内容。
  
  支持:
 1、冒泡排序
 2、选择排序
 3、快速排序

using System;

namespace 排序算法
{
/**//// <summary>
/// 排序模式
/// </summary>
public enum SortTypeEnum
{
ASC, //正序 A-Z
DESC //到序 Z-A
}

/**//// <summary>
/// SortClass 的摘要说明。
/// 对整形数组进行排序
/// 可以重写每个排序算法支持多类型
/// 注意:数组、对象,为传地址指针的形式
/// 执行方法后会便改原始数组内容。
///
/// 支持:
/// 1、冒泡排序
/// 2、选择排序
/// 3、快速排序
/// </summary>
public class SortClass
{
private SortTypeEnum oSortType = SortTypeEnum.ASC;

/**//// <summary>
/// 构造
/// </summary>
public SortClass(){;}

/**//// <summary>
/// 构造
/// </summary>
/// <param name="ste">排序模式</param>
public SortClass(SortTypeEnum ste)
{
this.oSortType = ste;
}

/**//// <summary>
/// 交换函数
/// </summary>
/// <param name="a">第一</param>
/// <param name="b">第二</param>
protected void Swap(ref int a,ref int b)
{
int c = a; a = b; b = c;
}

/**//// <summary>
/// 排序模式
/// </summary>
public SortTypeEnum SortType
{
get
{
return this.oSortType;
}
set
{
this.oSortType = value;
}
}

/**//// <summary>
/// 冒泡排序
/// </summary>
/// <param name="a">排序数组</param>
public void BubbleSort(int[] a)
{
int i = a.Length-1;
while(i>=0)
{
for(int j=0;j<a.Length-1;j++)
switch(oSortType)
{
case SortTypeEnum.ASC:
if(a[j]>a[j+1])
{
Swap(ref a[j],ref a[j+1]);
}
break;
case SortTypeEnum.DESC:
if(a[j]<a[j+1])
{
Swap(ref a[j],ref a[j+1]);
}
break;
}
i--;
}
}

/**//// <summary>
/// 选择排序
/// </summary>
/// <param name="a">排序数组</param>
public void SelectionSort(int[] a)
{
for(int i=0;i<a.Length-1;i++)
{
for(int j=a.Length-1;j>=i+1;j--)
{
switch(oSortType)
{
case SortTypeEnum.ASC:
if(a[i]>a[j])
{
Swap(ref a[i],ref a[j]);
}
break;
case SortTypeEnum.DESC:
if(a[i]<a[j])
{
Swap(ref a[i],ref a[j]);
}
break;
}

}
}
}

/**//// <summary>
/// 快速排序递归子过程
/// </summary>
/// <param name="a">排序数组</param>
/// <param name="iLo">低位</param>
/// <param name="iHi">高位</param>
private void QuickSortRecursion(int[] a,int iLo,int iHi)
{
int lo = iLo;
int hi = iHi;
int mid = a[(int)((lo+hi) >> 1)];
do
{
switch(oSortType)
{
case SortTypeEnum.ASC:
while(a[lo]<mid) lo ++;
while(a[hi]>mid) hi --;
break;
case SortTypeEnum.DESC:
while(a[lo]>mid) lo ++;
while(a[hi]<mid) hi --;
break;
}
if(lo<=hi)
{
Swap(ref a[lo],ref a[hi]);
lo++;
hi--;
}

}while(lo<hi);
if(hi>iLo)QuickSortRecursion(a,iLo,hi);
if(lo<iHi)QuickSortRecursion(a,lo,iHi);
}

/**//// <summary>
/// 快速排序
/// </summary>
/// <param name="a">排序数组</param>
public void QuickSort(int[] a)
{
QuickSortRecursion(a,0,a.Length-1);
}

}
}

 测试样例:

//数组
int[] test = new int[] { 9, 8, 7, 4, 3, 35, 4, 5, 3, 21, 1, 4, 57, 2, 123, 4, 0 };
//实例化
SortClass sc = new SortClass();
//排序模式
sc.SortType = SortTypeEnum.DESC;
//冒泡排序
sc.BubbleSort(test);
//选择排序
sc.SelectionSort(test);
//快速排序
sc.QuickSort(test);
//输出结果
textBox1.Text = "";
for (int i = 0; i < test.Length; i++)
{
textBox1.Text += test[i].ToString() + "\r\n";
}