First, the bubble sorting method is understood: is to compare the current position of the data in a collection with the next one, but the current position is greater than the next, then two positions are replaced until the sorting is complete
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespacemaopao{classProgram {Static voidSort (int[] sarray) { BOOLSW =true; Do{SW=false; for(inti =0; I < sarray.length-1; i++) { if(Sarray[i] > sarray[i +1]) { inttemp =Sarray[i]; Sarray[i]= Sarray[i +1]; Sarray[i+1] =temp; SW=true; } } } while(SW); } Static voidMain (string[] args) { int[] Sarray =New int[] { the, the, A,1,445, -, the,5 }; Sort (Sarray); foreach(varTempinchSarray) {Console.Write (temp+" "); } console.readkey (); } }}
Two, bubble sort expansion
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespacemaopao{classProgram {Static voidCommonsort<t> (t[] Sarray, func<t, T,BOOL>CompareMethod) { BOOLSW =true; Do{SW=false; for(inti =0; I < sarray.length-1; i++) { if(CompareMethod (Sarray[i], sarray[i +1]) {T temp=Sarray[i]; Sarray[i]= Sarray[i +1]; Sarray[i+1] =temp; SW=true; } } } while(SW); } Static voidMain (string[] args) {employee[] Employees=Newemployee[] {NewEmployee ("Zhang San", A), NewEmployee ("John Doe",234), NewEmployee ("Chen", -), NewEmployee ("Li Liu",234), NewEmployee ("Wang Qi", -) }; Commonsort<Employee>(employees, Employee.compare); foreach(Employee eminchemployees) {Console.WriteLine (EM); } console.readkey (); } }}
Class
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespacemaopao{classEmployee { Public stringName {Get;Private Set; } Public intComp {Get;Private Set; } PublicEmployee (stringNameintcomp) { This. Name =name; This. Comp =comp; } //returns True if E1 is greater than E2, otherwise false Public Static BOOLCompare (Employee E1, employee E2) {if(E1.comp > E2.comp)return true; return false; } Public Override stringToString () {returnName +":"+Comp; } }}
C # Bubble Sorting Method Learning