Witam,
Muszę posortować listę obiektów. Do sortowania wykorzystuję metodę bąbelkową. Program się wysypuje na linijce
ChairList.Reverse(i, i + 1);
wyświetlając komunikat:
Wartości przesunięcia i długości są spoza zakresu tablicy lub liczba przekracza liczbę elementów znajdujących się miedzy indeksem a końcem kolekcji źródłowej.
Jednak jak napiszę:
temp = ChairList[i];
ChairList[i] = ChairList[i + 1];
ChairList[i + 1] = temp;
to wszystko działa.
kod:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SortAplication
{
class Chair : IComparable<Chair>
{
public int chairLeg;
public int chairArea;
public int CompareTo(Chair ch)
{
return chairLeg.CompareTo(ch.chairLeg);
}
public Chair(int leg , int area ) {
chairLeg = leg;
chairArea = area;
}
~Chair() { }
}
class Program
{
static void Main(string[] args)
{
Random num = new Random();
List<Chair> ChairList = new List<Chair>();
for (int i = 0; i < 100; i++)
{
ChairList.Add(new Chair(num.Next(100), num.Next(100)));
Console.WriteLine(ChairList[i].chairLeg + "\t" + ChairList[i].chairArea);
}
/*bubble sort*/
int n = ChairList.Count;
Console.WriteLine(n);
do{
for (int i = 0; i < n - 1; i++)
{
if (ChairList[i].CompareTo(ChairList[i + 1]) > 0)
{
Chair temp = new Chair(0, 0);
temp = ChairList[i];
ChairList[i] = ChairList[i + 1];
ChairList[i + 1] = temp;
//ChairList.Reverse(i, i + 1); <-- TO NIE DZIAŁA
}
}
n--;
} while (n > 1);
//************//
Console.WriteLine("Posegregowana lista: ");
for (int i = 0; i < 100; i++)
{
ChairList.Add(new Chair(num.Next(100), num.Next(100)));
Console.WriteLine(ChairList[i].chairLeg + "\t" + ChairList[i].chairArea);
}
Console.ReadLine();
}
}
}
Jednocześnie chciałbym się zapytać o przydatność interfejsu IComparable
Mam takie zalecenie aby go wykorzystać. Ale załóżmy, że teraz dodaję klasę Table
i stoły także sortuję po ilości nóg. Jaką ja mam korzyść korzystania z interfejsu, skoro i tak musiałbym drugi raz zdefiniować metodę CompareTo(Table t)
dla klasy Table
.