三種常用C#排序算法
C#算法是C#語言學(xué)習(xí)中的重要一環(huán),C#排序算法無論在語言基礎(chǔ)還是數(shù)據(jù)結(jié)構(gòu)中都是必不可少的知識,下面我們來看著名的冒泡排序、選擇排序和插入排序,這是最常用的三種C#排序算法。
C#排序算法之冒泡排序   
    
一下是C#開發(fā)出冒泡排序算法。希望能為C#語言的學(xué)習(xí)者帶來一些益處。不要忘了,學(xué)語言要花大力氣學(xué)數(shù)據(jù)結(jié)構(gòu)和算法。  
- using System;
 - namespace BubbleSorter
 - {
 - public class BubbleSorter
 - {
 - public void Sort(int [] list)
 - {
 - int i,j,temp;
 - bool done=false;
 - j=1;
 - while((j<list.Length)&&(!done))
 - {
 - done=true;
 - for(i=0;i<list.Length-j;i++)
 - {
 - if(list[i]>list[i+1])
 - {
 - done=false;
 - temp=list[i];
 - list[i]=list[i+1];
 - list[i+1]=temp;
 - }
 - }
 - j++;
 - }
 - }
 - }
 - public class MainClass
 - {
 - public static void Main()
 - {
 - int[] iArrary=new int[]{1,5,13,6,10,55,99,2,87,12,34,75,33,47};
 - BubbleSorter sh=new BubbleSorter();
 - sh.Sort(iArrary);
 - for(int m=0;m<iArrary.Length;m++)
 - Console.Write("{0} ",iArrary[m]);
 - Console.WriteLine();
 - }
 - }
 - }
 
C#排序算法之選擇排序
C#選擇排序算法主要應(yīng)用在數(shù)據(jù)庫查詢和文本對比方面,應(yīng)用此算法需要考慮到程序的內(nèi)存占用方面的效率。一下是代碼示例:
- using System;
 - namespace SelectionSorter
 - {
 - public class SelectionSorter
 - {
 - private int min;
 - public void Sort(int [] list)
 - {
 - for(int i=0;i<list.Length-1;i++)
 - {
 - min=i;
 - for(int j=i+1;j<list.Length;j++)
 - {
 - if(list[j]<list[min])
 - min=j;
 - }
 - int t=list[min];
 - list[min]=list[i];
 - list[i]=t;
 - }
 - }
 - }
 - public class MainClass
 - {
 - public static void Main()
 - {
 - int[] iArrary=new int[]{1,5,3,6,10,55,9,2,87,12,34,75,33,47};
 - SelectionSorter ss=new SelectionSorter();
 - ss.Sort(iArrary);
 - for(int m=0;m<iArrary.Length;m++)
 - Console.Write("{0} ",iArrary[m]);
 - Console.WriteLine();
 - }
 - }
 - }
 
C#排序算法之插入排序     
    
C#插入排序算法主要對應(yīng)項(xiàng)目需求中的結(jié)果集插入,文本插入和數(shù)據(jù)庫插入等。下面的程序通過多態(tài)性來實(shí)現(xiàn)C#插入排序。
- using System;
 - namespace InsertionSorter
 - {
 - public class InsertionSorter
 - {
 - public void Sort(int [] list)
 - {
 - for(int i=1;i<list.Length;i++)
 - {
 - int t=list[i];
 - int j=i;
 - while((j>0)&&(list[j-1]>t))
 - {
 - list[j]=list[j-1];
 - --j;
 - }
 - list[j]=t;
 - }
 - }
 - }
 - public class MainClass
 - {
 - public static void Main()
 - {
 - int[] iArrary=new int[]{1,13,3,6,10,55,98,2,87,12,34,75,33,47};
 - InsertionSorter ii=new InsertionSorter();
 - ii.Sort(iArrary);
 - for(int m=0;m<iArrary.Length;m++)
 - Console.Write("{0}",iArrary[m]);
 - Console.WriteLine();
 - }
 - }
 - }
 
【編輯推薦】















 
 
 








 
 
 
 