using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sort
{
class Program
{
staticvoid Main(string[] args)
{
List<Person> persons=new List<Person>()
{
new Person(4),
new Person(3),
new Person(2),
new Person(5)
};
BubbleSort(persons,Person.Compare);
foreach (Person person in persons)
{
Console.WriteLine(person);
}
Console.ReadKey();
}
staticvoid BubbleSort<T>(List<T> list,Func<T,T,bool> Compare)
{
for (int i = 0; i < list.Count; i++)
{
for (int j = 0; j < list.Count - i - 1; j++)
{
if (Compare(list[j],list[j+1]))
{
T temp = list[j+1];
list[j + 1] = list[j];
list[j] = temp;
}
}
}
}
class Person
{
privateint num;
public Person(int Num)
{
num = Num;
}
publicstaticbool Compare(Person p1, Person p2)
{
if (p1.num > p2.num)
returntrue;
else
{
returnfalse;
}
}
public override string ToString()
{
return num.ToString();
}
}
}
}
選擇排序
在要排序的一組數中,選出最小的一個數與第一個位置的數交換;
然後在剩下的數當中再找最小的與第二個位置的數交換,如此循環到倒數第二個數和最後一個數比較爲止。
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SelectSort
{
class Program
{
staticvoid Main(string[] args)
{
int[] array=newint[4]{2,3,4,1};
Sort(array);
foreach (int temp in array)
{
Console.WriteLine(temp);
}
Console.ReadKey();
}
staticvoid Sort(int[] array)
{
for (int i = 0; i < array.Length-1; i++)
{
int iTemp = array[i];
int iPos = i;
for (int j = i+1; j < array.Length; j++)
{
if (array[j] < iTemp)
{
iTemp = array[j];
iPos = j;
}
}
array[iPos] = array[i];
array[i] = iTemp;
}
}
}
}
直接插入排序
直接插入排序:在要排序的一組數中,假設前面(n-1) [n>=2] 個數已經是排好順序的
現在要把第n個數插到前面的有序數中,使得這n個數也是排好順序的。如此反覆循環,直到全部排好順序。
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InsertSort
{
class Program
{
staticvoid Main(string[] args)
{
int[] array = newint[4] { 2, 3, 4, 1 };
//不能再靜態方法裏調用非靜態成員
Sort(array);
foreach (int temp in array)
{
Console.WriteLine(temp);
}
Console.ReadKey();
}
staticvoid Sort(int[] array)
{
//外層循環標示並決定待比較的數值(array[i])for (int i = 1; i < array.Length; i++)
{
int j = i - 1;
int temp = array[i];
//內層循環爲待比較的數值確定其最終位置,當前一數字(array[j])比待比較的數值大的情況下繼續循環,//直到找到比待比較數值小的並將待比較數值置入其後一位置,結束該次循環for (; j >= 0 && array[j]>temp; j--)
{
array[j + 1] = array[j];
}
array[j + 1] = temp;
}
}
}
}