Sorting is one of the most important operations in programming and software development. In C# programming, sorting arrays helps organize data in ascending or descending order, making it easier to search, analyze, and display information efficiently. Whether you are preparing for interviews, building enterprise applications, or working on data-driven systems, understanding how to sort arrays in C# is a fundamental skill.
This detailed guide explains everything about C# sort array techniques, including built-in methods, custom sorting logic, sorting in ascending and descending order, sorting string arrays, numeric arrays, object arrays, and advanced comparison techniques.
What is Sorting in C#?
Sorting in C# refers to arranging elements of an array or collection in a specific order, typically:
Sorting improves data readability and supports efficient searching algorithms like binary search.
In C#, sorting is primarily done using the built-in Array.Sort() method, which belongs to the System namespace.
Sorted arrays allow the use of binary search which significantly improves performance.
Sorting makes reports, dashboards, and output displays user-friendly.
Sorting helps optimize large datasets in enterprise-level C# applications.
Sorting algorithms are frequently asked in C# interview questions.
The simplest way to sort arrays in C# is using the built-in Array.Sort() method.
Array.Sort(arrayName);
using System;
class Program
{
static void Main()
{
int[] numbers = { 5, 2, 9, 1, 3 };
Array.Sort(numbers);
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}
1 2 3 5 9
By default, Array.Sort() sorts elements in ascending order.
To sort an array in descending order, first sort in ascending order and then reverse it.
using System;
class Program
{
static void Main()
{
int[] numbers = { 5, 2, 9, 1, 3 };
Array.Sort(numbers);
Array.Reverse(numbers);
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}
9 5 3 2 1
This is a common approach for implementing descending order in C#.
C# can also sort string arrays alphabetically.
using System;
class Program
{
static void Main()
{
string[] names = { "Ravi", "Anita", "Kiran", "Meena" };
Array.Sort(names);
foreach (string name in names)
{
Console.WriteLine(name);
}
}
}
Anita Kiran Meena Ravi
String sorting follows alphabetical order by default.
Sometimes you need custom sorting logic. In such cases, use a Comparison delegate.
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 25, 3, 40, 15 };
Array.Sort(numbers, (a, b) => b.CompareTo(a));
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}
This directly sorts the array in descending order without using Array.Reverse().
To sort custom objects, implement the IComparable interface.
using System;
class Student : IComparable<Student>
{
public string Name { get; set; }
public int Marks { get; set; }
public int CompareTo(Student other)
{
return this.Marks.CompareTo(other.Marks);
}
}
class Program
{
static void Main()
{
Student[] students = {
new Student { Name = "Asha", Marks = 85 },
new Student { Name = "Raj", Marks = 75 },
new Student { Name = "Vijay", Marks = 95 }
};
Array.Sort(students);
foreach (var student in students)
{
Console.WriteLine(student.Name + " " + student.Marks);
}
}
}
This sorts students by marks in ascending order.
LINQ provides powerful sorting capabilities.
using System;
using System.Linq;
class Program
{
static void Main()
{
int[] numbers = { 5, 8, 2, 9, 1 };
var sorted = numbers.OrderBy(n => n);
foreach (var num in sorted)
{
Console.WriteLine(num);
}
}
}
var sortedDesc = numbers.OrderByDescending(n => n);
LINQ is widely used in modern C# programming tutorials.
Multi-dimensional arrays cannot be directly sorted. Convert to a single dimension or use custom logic.
int[,] matrix = {
{ 3, 1 },
{ 4, 2 }
};
You must flatten it before sorting.
The internal sorting algorithm used by Array.Sort() is Introspective Sort (Introsort).
This makes C# array sorting highly efficient.
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = 0; j < arr.Length - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = 0; i < arr.Length - 1; i++)
{
int minIndex = i;
for (int j = i + 1; j < arr.Length; j++)
{
if (arr[j] < arr[minIndex])
minIndex = j;
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
for (int i = 1; i < arr.Length; i++)
{
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
It is a built-in method used to sort arrays in ascending order.
Use Array.Reverse() or custom comparison.
O(n log n)
Yes, using IComparable or IComparer.
Sorting arrays in C# is a crucial programming skill. Whether you are using Array.Sort(), LINQ methods, or implementing custom sorting algorithms, mastering sorting helps you build efficient and scalable applications. From beginner-level examples to advanced object sorting techniques, this guide covered everything required to understand C# array sorting examples in depth.
By practicing these concepts, you will strengthen your foundation in C# programming and improve your problem-solving abilities.
C# is primarily used on the Windows .NET framework, although it can be applied to an open source platform. This highly versatile programming language is an object-oriented programming language (OOP) and comparably new to the game, yet a reliable crowd pleaser.
The C# language is also easy to learn because by learning a small subset of the language you can immediately start to write useful code. More advanced features can be learnt as you become more proficient, but you are not forced to learn them to get up and running. C# is very good at encapsulating complexity.
The decision to opt for C# or Node. js largely hinges on the specific requirements of your project. If you're developing a CPU-intensive, enterprise-level application where stability and comprehensive tooling are crucial, C# might be your best bet.
C# is part of .NET, a free and open source development platform for building apps that run on Windows, macOS, Linux, iOS, and Android. There's an active community answering questions, producing samples, writing tutorials, authoring books, and more.
Copyrights © 2024 letsupdateskills All rights reserved