Материал из .Net Framework эксперт
Bubble sort object array
using System;
delegate bool CompareOp(object lhs, object rhs);
class MainEntryPoint {
static void Main() {
Employee[] employees = {
new Employee("B", 20000),
new Employee("E", 10000),
new Employee("D", 25000),
new Employee("W", (decimal)1000000.38),
new Employee("F", 23000),
new Employee("R"", 50000)};
CompareOp employeeCompareOp = new CompareOp(Employee.RhsIsGreater);
BubbleSorter.Sort(employees, employeeCompareOp);
for (int i = 0; i < employees.Length; i++)
Console.WriteLine(employees[i].ToString());
Console.ReadLine();
}
}
class Employee{
private string name;
private decimal salary;
public Employee(string name, decimal salary) {
this.name = name;
this.salary = salary;
}
public override string ToString() {
return string.Format(name + ", {0:C}", salary);
}
public static bool RhsIsGreater(object lhs, object rhs) {
Employee empLhs = (Employee)lhs;
Employee empRhs = (Employee)rhs;
return (empRhs.salary > empLhs.salary) ? true : false;
}
}
class BubbleSorter {
static public void Sort(object[] sortArray, CompareOp gtMethod) {
for (int i = 0; i < sortArray.Length; i++) {
for (int j = i + 1; j < sortArray.Length; j++) {
if (gtMethod(sortArray[j], sortArray[i])) {
object temp = sortArray[i];
sortArray[i] = sortArray[j];
sortArray[j] = temp;
}
}
}
}
}
Your own quick sort
using System;
using System.Collections.Generic;
class MainClass{
public static void Main(){
MyQuickSort<int> iSort = new MyQuickSort<int>(new int[]{2,1,3});
iSort.Sort();
}
}
class MyQuickSort<T> where T : IComparable
{
T[] data;
public MyQuickSort(T[] values)
{
data = values;
}
private void doSort(int first, int last)
{
if (first == last)
{
return;
}
else
{
int pivot = getPivotPoint(first, last);
if (pivot > first)
doSort(first, pivot - 1);
if (pivot < last)
doSort(pivot + 1, last);
}
}
private int getPivotPoint(int first, int last)
{
int pivot = first;
int start = first;
int end = last;
if (last - first >= 1){
while (end > start)
{
while (data[pivot].rupareTo(data[start]) >= 0 && start <= last && end > start)
start++;
while (data[pivot].rupareTo(data[end]) <= 0 && end >= first && end >= start)
end--;
if (end > start)
swap(start, end);
}
swap(first, end);
doSort(first, end - 1);
}
return end;
}
private void swap(int pos1, int pos2)
{
T temp;
temp = data[pos1];
data[pos1] = data[pos2];
data[pos2] = temp;
}
public void Sort()
{
int len = data.Length;
if (len < 2) // Enough to sort?
return;
doSort(0, data.Length - 1);
}
}