利用委托实现对某对象进行排序,要求实现冒泡排序和选择排序,以Car类型对象为例,其中Car类包括两个字段,name和price,最后在main方法中实现用冒泡排序和选择排序对Car对象的名称和价格进行排序。
第一种方法
1编写代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 委托排序
{
public class Car//Car类
{
public string name;
public double price;
public Car(string name,double price)
{
this.name = name;
this.price = price;
}
public static void nameSort(List<Car> x)//根据名称冒泡排序
{
for (int i = 0; i < x.Count - 1; i++)
{
Car temp;
for (int j = 0; j < x.Count - 1; j++)
{
if (string.Compare(x[j].name,x[j + 1].name)>0)
{
temp = x[j + 1];
x[j + 1] = x[j];
x[j] = temp;
}
}
}
}
public static void priceSort(List<Car> x)//根据价格冒泡排序
{
for (int i = 0; i < x.Count - 1;i++ )
{
Car temp;
for (int j = 0; j < x.Count - 1;j++ )
{
if (x[j].price > x[j + 1].price)
{
temp=x[j+1];
x[j + 1] = x[j];
x[j] = temp;
}
}
}
}
public static void nameSelectSort(List<Car> x)//根据名称选择排序
{
for (int i = 0; i < x.Count - 1; i++)
{
Car temp;
int pos = 0;
for (int j = i+1; j < x.Count; j++)
{