using System; using System.Collections; namespace ArraySort { public class DataElement { public int value; public DataElement() {} public DataElement(int value) { this.value = value; } } public class DataElementComparer : IComparer { public int Compare(object x, object y) { return ((DataElement)x).value.CompareTo(((DataElement)y).value); } } public class Client { public static void Main() { int[] myArray = {9,8,7,6,5,4,3,2,1,0}; DataElement[] d = new DataElement[10]; for (int i = 0; i < myArray.Length; i++) d[i] = new DataElement(myArray[i]); Console.WriteLine("排序前"); for (int i = 0;i < myArray.Length;i++) { Console.Write(d[i].value +","); } Array.Sort(d, new DataElementComparer()); //排序实例化
Console.WriteLine("\n排序后"); for (int i = 0; i < myArray.Length; i++) Console.Write(d[i].value + ", "); Console.WriteLine(); } } }
sort(array1,array1.Length); private void sort(int[] a,int length)
{
int i,j,t;
for(i=0;i<length-1;i++)
{
t=i;
for(j=i+1;j<length;j++)
{
if(a[j]<a[t])
{
t=j;
}
}
if(t!=i)
{
j=a[i];
a[i]=a[t];
a[t]=j;
}
}
}
Array.Sort(数组名);
如交换A和B
A=A+B;
B=A-B;
A=A-B;
using System.Collections;
namespace ArraySort
{
public class DataElement
{
public int value;
public DataElement() {}
public DataElement(int value) { this.value = value; }
} public class DataElementComparer : IComparer
{
public int Compare(object x, object y)
{
return ((DataElement)x).value.CompareTo(((DataElement)y).value);
}
} public class Client
{
public static void Main()
{
int[] myArray = {9,8,7,6,5,4,3,2,1,0};
DataElement[] d = new DataElement[10]; for (int i = 0; i < myArray.Length; i++)
d[i] = new DataElement(myArray[i]); Console.WriteLine("排序前");
for (int i = 0;i < myArray.Length;i++)
{
Console.Write(d[i].value +",");
} Array.Sort(d, new DataElementComparer()); //排序实例化
Console.WriteLine("\n排序后");
for (int i = 0; i < myArray.Length; i++)
Console.Write(d[i].value + ", ");
Console.WriteLine();
}
}
}
<C# primer>里面介绍如何用委托进行快速排序,还是很值研究几分钟的。