C# Sort Arrays

Welcome to The Coding College! In this tutorial, we’ll explore how to sort arrays in C#. Sorting is an essential operation when working with data, and C# provides robust and straightforward methods to sort arrays effectively.

Why Sort Arrays?

Sorting arrays is crucial in many scenarios, such as:

  • Organizing data for efficient searching.
  • Displaying information in a logical order.
  • Preparing data for algorithms that require sorted input.

C# provides built-in methods like Array.Sort() to make sorting easy and efficient.

Sorting Arrays in C#

C# offers a built-in method, Array.Sort(), that can be used to sort arrays in ascending order. You can also customize the sorting logic if needed.

1. Sorting Numeric Arrays

Example:

using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 5, 2, 8, 1, 3 };

        Console.WriteLine("Original Array:");
        foreach (int num in numbers)
        {
            Console.Write(num + " ");
        }

        // Sort the array in ascending order
        Array.Sort(numbers);

        Console.WriteLine("\n\nSorted Array:");
        foreach (int num in numbers)
        {
            Console.Write(num + " ");
        }
    }
}

Output:

Original Array:
5 2 8 1 3

Sorted Array:
1 2 3 5 8

2. Sorting String Arrays

Example:

using System;

class Program
{
    static void Main()
    {
        string[] fruits = { "Banana", "Apple", "Cherry", "Date" };

        Console.WriteLine("Original Array:");
        foreach (string fruit in fruits)
        {
            Console.Write(fruit + " ");
        }

        // Sort the array in alphabetical order
        Array.Sort(fruits);

        Console.WriteLine("\n\nSorted Array:");
        foreach (string fruit in fruits)
        {
            Console.Write(fruit + " ");
        }
    }
}

Output:

Original Array:
Banana Apple Cherry Date

Sorted Array:
Apple Banana Cherry Date

3. Sorting Arrays in Descending Order

To sort an array in descending order, you can combine Array.Sort() with Array.Reverse().

Example:

using System;

class Program
{
    static void Main()
    {
        int[] scores = { 85, 90, 78, 92, 88 };

        Console.WriteLine("Original Array:");
        foreach (int score in scores)
        {
            Console.Write(score + " ");
        }

        // Sort the array in ascending order
        Array.Sort(scores);

        // Reverse the array to get descending order
        Array.Reverse(scores);

        Console.WriteLine("\n\nSorted Array (Descending):");
        foreach (int score in scores)
        {
            Console.Write(score + " ");
        }
    }
}

Output:

Original Array:
85 90 78 92 88

Sorted Array (Descending):
92 90 88 85 78

4. Sorting Multi-Dimensional Arrays

Sorting multi-dimensional arrays requires custom logic since Array.Sort() does not work directly on them.

Example: Sorting a 2D Array by Rows

using System;

class Program
{
    static void Main()
    {
        int[,] matrix = {
            { 5, 2, 8 },
            { 3, 9, 1 },
            { 4, 7, 6 }
        };

        Console.WriteLine("Original 2D Array:");
        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                Console.Write(matrix[i, j] + " ");
            }
            Console.WriteLine();
        }

        // Sort each row
        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            int[] row = new int[matrix.GetLength(1)];
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                row[j] = matrix[i, j];
            }

            Array.Sort(row);

            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                matrix[i, j] = row[j];
            }
        }

        Console.WriteLine("\nSorted 2D Array by Rows:");
        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                Console.Write(matrix[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}

Output:

Original 2D Array:
5 2 8
3 9 1
4 7 6

Sorted 2D Array by Rows:
2 5 8
1 3 9
4 6 7

Custom Sorting with Comparer

You can define custom sorting logic using the IComparer interface for more advanced scenarios.

Example: Custom Sorting Strings by Length

using System;
using System.Collections;

class Program
{
    static void Main()
    {
        string[] words = { "apple", "kiwi", "banana", "grape" };

        Console.WriteLine("Original Array:");
        foreach (string word in words)
        {
            Console.Write(word + " ");
        }

        // Sort array by string length
        Array.Sort(words, new StringLengthComparer());

        Console.WriteLine("\n\nSorted Array (By Length):");
        foreach (string word in words)
        {
            Console.Write(word + " ");
        }
    }
}

class StringLengthComparer : IComparer
{
    public int Compare(object x, object y)
    {
        return ((string)x).Length.CompareTo(((string)y).Length);
    }
}

Output:

Original Array:
apple kiwi banana grape

Sorted Array (By Length):
kiwi grape apple banana

Common Mistakes to Avoid

  1. Not Reversing for Descending Order:
    Remember to use Array.Reverse() after sorting if descending order is needed.
  2. Modifying Arrays While Iterating:
    Avoid modifying the array while sorting it to prevent runtime errors.
  3. Sorting Multi-Dimensional Arrays Directly:
    Use custom logic for multi-dimensional arrays, as Array.Sort() doesn’t directly support them.

Conclusion

Sorting arrays in C# is a powerful tool for organizing and processing data. Whether you’re working with numbers, strings, or custom objects, C# offers versatile sorting options to meet your needs. Experiment with the methods shown here to become confident in handling sorted data.

For more coding tutorials, visit The Coding College, where we make learning coding simple and enjoyable.

Leave a Comment