C#: Ordenando una lista genérica
19/01/2009
Deja un comentario
El siguiente código muestra el ordenamiento de una lista genérica, siendo necesario que los objetos implementen la interfaz Icomparable.
using System;
using System.Collections.Generic;
namespace nitrogeno
{
class Program
{
static void Main(string[] args)
{
IList<string> list1 = new List<string>();
list1.Add("Casa"); // 1
list1.Add("Auto"); // 2
list1.Add("Arbol"); // 3
list1.Add("Sapo"); // 4
list1.Add("Nuevo"); // 5
SortList.Bubble<string>(list1);
foreach (string item in list1)
Console.WriteLine("{0}", item);
Console.WriteLine();
IList<int> list2 = new List<int>();
list2.Add(5); // 1
list2.Add(2); // 2
list2.Add(3); // 3
list2.Add(1); // 4
list2.Add(4); // 5
SortList.Bubble<int>(list2);
foreach (int item in list2)
Console.WriteLine("{0}", item);
}
}
public class SortList
{
public static IList<T> Bubble<T>(IList<T> list)
where T : IComparable
{
T tmp;
for (int i = 0; i < list.Count; i++)
{
for (int x = 0; x < list.Count - (i + 1); x++)
{
if (list[x].CompareTo(list[x + 1]) > 0)
{
tmp = list[x + 1];
list[x + 1] = list[x];
list[x] = tmp;
}
}
}
return list;
}
}
}
Categorías:burbuja, C#, Generico, Icomparable, Lista, ordenamiento, Programación