Algoritmos de Ordenação
What is it and why? (a real-life analogy)
Imagine you are a physical education teacher, and you have a stack of cards with 100-meter sprint results. The cards are in disarray: first Petya (12.5 sec), then Masha (11.2 sec), then Vasya (15.1 sec). To find out who is the fastest, you need to order these cards by time — from best to worst. This is sorting.
In programming, sorting is the process of rearranging the elements of an array or list in a specific order (usually ascending or descending). Why is this needed? Imagine you have a phone book with 1000 contacts, but they are recorded in the order you added them. Finding "Ivanov" would be very difficult. But if you sort alphabetically — everything becomes simple.
Sorting is a basic skill that is used everywhere: from searching in Google to sorting photos by date on your phone. No serious program can do without it.
In real life, we constantly sort: we arrange books alphabetically, sort clothes by color, prioritize tasks by urgency. Computers do the same thing, but much faster — millions of elements in fractions of a second.
Theory: how it works from the inside
Let's look "under the hood" and understand how a computer knows which element is larger and which is smaller. At the heart of any sorting lies comparison. We take two elements and ask: "Is the first one greater than the second?" If yes — we swap them. If no — we leave them as is.
But simply comparing everything in a row is inefficient. Imagine you have 1000 numbers, and you compare each with every other. That's 1,000,000 operations! Smart algorithms do this more cleverly.
Main types of sorting (brief overview)
| Name | Complexity (Time) | How it works (very briefly) |
|---|---|---|
| Bubble Sort | O(n²) — slow | The largest element "bubbles up" like a bubble in water |
| Insertion Sort | O(n²) — average | Like arranging cards in your hand: take a card and insert it into the right place |
| Selection Sort | O(n²) — average | Find the smallest element and put it at the beginning |
| Quick Sort | O(n log n) — fast | Divide the array in half, sort each half separately |
| Merge Sort | O(n log n) — fast | Divide down to one element, then assemble back already sorted |
Important: O(n²) is "quadratic complexity". If there are 10 elements, 100 operations are needed. If 1000 — 1,000,000. O(n log n) is "linearithmic". For 1000 elements, only ~10,000 operations are needed. The difference is huge!
How does a computer compare elements?
In C#, the IComparable interface or the Comparison delegate is used for comparison. By default, numbers are compared by value, strings alphabetically (lexicographically). But you can write your own comparison logic — for example, sorting people by age rather than by name.
Syntax in C# (.NET): all forms and variants
In C#, there are several ways to sort data. Let's go through them all — from the simplest to the more complex.
1. Built-in Array.Sort() method
The simplest way for arrays. Works "out of the box" for numbers, strings, and other built-in types.
int[] numbers = { 5, 3, 8, 1, 9 };
Array.Sort(numbers); // Now numbers = { 1, 3, 5, 8, 9 }
// Sorting happens "in place" — the original array is modified
2. List.Sort() method
For lists (List
List<string> names = new List<string> { "Ivan", "Anna", "Petr" };
names.Sort(); // Now: "Anna", "Ivan", "Petr"
3. LINQ: OrderBy() and OrderByDescending()
The most flexible way. Does not modify the original collection, but returns a new sorted one.
int[] numbers = { 5, 3, 8, 1, 9 };
var sorted = numbers.OrderBy(n => n).ToArray(); // { 1, 3, 5, 8, 9 }
var sortedDesc = numbers.OrderByDescending(n => n).ToArray(); // { 9, 8, 5, 3, 1 }
4. Sorting with a custom comparer
When you need to sort by your own rules (for example, by string length).
string[] words = { "cat", "elephant", "I", "hippopotamus" };
Array.Sort(words, (a, b) => a.Length.CompareTo(b.Length));
// Result: "I", "cat", "elephant", "hippopotamus" (by ascending length)
5. Sorting objects by property
Most often we work not with numbers, but with objects. For example, sorting a list of students by age.
public class Student {
public string Name { get; set; }
public int Age { get; set; }
}
List<Student> students = new List<Student> {
new Student { Name = "Petya", Age = 20 },
new Student { Name = "Masha", Age = 18 },
new Student { Name = "Vasya", Age = 22 }
};
// Sort by age
students.Sort((s1, s2) => s1.Age.CompareTo(s2.Age));
6. Implementing IComparable
If you want your class to be "able" to sort by default.
public class Student : IComparable<Student> {
public string Name { get; set; }
public int Age { get; set; }
public int CompareTo(Student other) {
return this.Age.CompareTo(other.Age); // By age
}
}
// Now you can simply: students.Sort();