C#中四种排序算法

一、冒泡排序(Bubble)

 1using System; 
 2
 3namespace BubbleSorter 
 4{ 
 5public class BubbleSorter 
 6{ 
 7public void Sort(int[] list) 
 8{ 
 9int i,j,temp; 
10bool d; 
11j=1; 
12while((j<list.Length)&&(!done)) 
13{ 
14d; 
15for(i=0;i<list.Length-j;i++) 
16{ 
17if(list[i]>list[i+1]) 
18{ 
19d; 
20temp=list[i]; 
21list[i]=list[i+1]; 
22list[i+1]=temp; 
23}
 
24}
 
25j++; 
26}
 
27}
 
28}
 
29
30public class MainClass 
31{ 
32public static void Main() 
33{ 
34int[] iArrary=new int[]{1,5,13,6,10,55,99,2,87,12,34,75,33,47}; 
35BubbleSorter sh=new BubbleSorter(); 
36sh.Sort(iArrary); 
37for(int m=0;m<iArrary.Length;m++) 
38Console.Write("{0} ",iArrary[m]); 
39Console.WriteLine(); 
40}
 
41}
 
42}
 
43

二、选择排序(Selection)
 1using System; 
 2
 3namespace SelectionSorter 
 4{ 
 5public class SelectionSorter 
 6{ 
 7private int min; 
 8public void Sort(int [] list) 
 9{ 
10for(int i=0;i<list.Length-1;i++) 
11{ 
12min=i; 
13for(int j=i+1;j<list.Length;j++) 
14{ 
15if(list[j]<list[min]) 
16min=j; 
17}
 
18int t=list[min]; 
19list[min]=list[i]; 
20list[i]=t; 
21}
 
22}
 
23}
 
24
25public class MainClass 
26{ 
27public static void Main() 
28{ 
29int[] iArrary = new int[]{1,5,3,6,10,55,9,2,87,12,34,75,33,47}; 
30SelectionSorter ss=new SelectionSorter(); 
31ss.Sort(iArrary); 
32for (int m=0;m<iArrary.Length;m++) 
33Console.Write("{0} ",iArrary[m]); 
34Console.WriteLine(); 
35}
 
36}
 
37}
 
38

三、插入排序(InsertionSorter)
 1using System; 
 2
 3namespace InsertionSorter 
 4{ 
 5public class InsertionSorter 
 6{ 
 7public void Sort(int [] list) 
 8{ 
 9for(int i=1;i<list.Length;i++) 
10{ 
11int t=list[i]; 
12int j=i; 
13while((j>0)&&(list[j-1]>t)) 
14{ 
15list[j]=list[j-1]; 
16--j; 
17}
 
18list[j]=t; 
19}
 
20}
 
21}
 
22
23public class MainClass 
24{ 
25public static void Main() 
26{ 
27int[] iArrary=new int[]{1,13,3,6,10,55,98,2,87,12,34,75,33,47}; 
28InsertionSorter ii=new InsertionSorter(); 
29ii.Sort(iArrary); 
30for(int m=0;m<iArrary.Length;m++) 
31Console.Write("{0}",iArrary[m]); 
32Console.WriteLine(); 
33}
 
34}
 
35}
 

四、希尔排序(ShellSorter)
 1 using System; 
 2 
 3 namespace ShellSorter 
 4 { 
 5 public class ShellSorter 
 6 { 
 7 public void Sort(int [] list) 
 8 { 
 9 int inc; 
10 for(inc=1;inc<=list.Length/9;inc=3*inc+1); 
11 for(;inc>0;inc/=3) 
12 { 
13 for(int i=inc+1;i<=list.Length;i+=inc) 
14 { 
15 int t=list[i-1]; 
16 int j=i; 
17 while((j>inc)&&(list[j-inc-1]>t)) 
18 { 
19 list[j-1]=list[j-inc-1]; 
20 j-=inc; 
21 } 
22 list[j-1]=t; 
23 } 
24 } 
25 } 
26 } 
27 
28 public class MainClass 
29 { 
30 public static void Main() 
31 { 
32 int[] iArrary=new int[]{1,5,13,6,10,55,99,2,87,12,34,75,33,47}; 
33 ShellSorter sh=new ShellSorter(); 
34 sh.Sort(iArrary); 
35 for(int m=0;m<iArrary.Length;m++) 
36 Console.Write("{0} ",iArrary[m]); 
37 Console.WriteLine(); 
38 } 
39 } 
40 }
41 
posted @ 2007-11-30 16:37  键盘上的烟灰  阅读(697)  评论(0)    收藏  举报