I searched an answer for my question but I could not find anything. I am sorry if there is a similar theme. So I need to sort a list of objects by their property and I have to use bubble sort. How can I make it without using methods like "list.sort". Thank you in advance!
using System;
using System.Collections.Generic;
class Animals
{
public int id { get; set; }
public string name { get; set; }
public string color { get; set; }
public int age { get; set; }
}
class Program
{
static void Main()
{
Console.Write("How much animals you want to add?: ");
int count = int.Parse(Console.ReadLine());
var newAnimals = new List<Animals>(count);
Animals animal = new Animals();
newAnimals.Add(animal);
for (int i = 0; i < count; i++)
{
newAnimals[i].id = i;
Console.Write("Write name for animal: " + i + ": ");
newAnimals[i].name = Console.ReadLine();
Console.Write("Write age for animal: " + i + ": ");
newAnimals[i].age = int.Parse(Console.ReadLine());
Console.Write("Write color for animal: " + i + ": ");
newAnimals[i].color = Console.ReadLine();
newAnimals.Add(new Animals() { id = 1, name = "name" });
}
Console.WriteLine("Name \tAge \tColor");
for (int i = 0; i < count; i++)
{
Console.WriteLine(newAnimals[i].name + "\t" + newAnimals[i].age + "\t" + newAnimals[i].color);
}
Console.ReadLine();
}
}
Console.WriteLine("Name \tAge \tColor");
for (int i = 0; i < count; i++)
{
Console.WriteLine(newAnimals[i].name + "\t" + newAnimals[i].age + "\t" + newAnimals[i].color);
}
Console.ReadLine();
}
}
here you go (assuming that you want to sort by id)
for (int i = 0; i < newAnimals.Count; i++)
{
for (int j = 1; j <= i; j++)
{
if (newAnimals[j - 1].id > newAnimals[j].id)
{
Animals temp = newAnimals[j - 1];
newAnimals[j - 1] = newAnimals[j];
newAnimals[j] = temp;
}
}
}
Generic, with dynamic property selector :
public static class MyExtensions
{
public static void BubbleSort<T>(this List<T> list, Func<T, int> selector)
{
while (true)
{
bool changed = false;
for (int i = 1; i < list.Count; i++)
{
if (selector(list[i - 1]) > selector(list[i]))
{
T temp = list[i - 1];
list[i - 1] = list[i];
list[i] = temp;
changed = true;
}
}
if (!changed)
break;
}
}
}
Usage:
unsortedList.BubbleSort(x => x.SortProperty);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.