CodeBlanks Logo Icon CodeBlanks

Array.Sort

C# course · Beginner · Lesson 59/116

Learn to sort an array in ascending order with Array.Sort.

Array.Sort

The Array.Sort method sorts an array in place in ascending order. It does not return a new array; it rearranges the elements of the existing array. Numbers go from smallest to largest, strings alphabetically.

For example, after int[] nums = { 5, 2, 8, 1 }; Array.Sort(nums);, the nums array becomes { 1, 2, 5, 8 }. Because sorting changes the array directly, you cannot reach the old order afterwards.

Sort order and types

Array.Sort always sorts in ascending order. For descending order, first call Array.Sort and then reverse with Array.Reverse.

For string arrays the sort is alphabetical, sensitive to culture and case. The array string[] names = { "Zeynep", "Ayşe" } becomes { "Ayşe", "Zeynep" } after sorting.

Exercise Sort scores and print the first element

Sort the given int[] scores = { 78, 92, 65, 88 }; array with Array.Sort. Then print the first element (scores[0]) with Console.WriteLine.

Show example solution
Sort the array with Array.Sort(scores); and print the first element with Console.WriteLine(scores[0]);.
Example solution:
using System;

class Program
{
    static void Main()
    {
        int[] scores = { 78, 92, 65, 88 };
        // Sort the scores and print the first element
        Array.Sort(scores);
        Console.WriteLine(scores[0]);
    }
}

Test yourself

  1. What does nums[0] print after Array.Sort?

    int[] nums = { 5, 2, 8, 1 };
    Array.Sort(nums);
    Console.WriteLine(nums[0]);
    • 1
    • 5
    • 8
    • 0
    Show answer

    1 — Correct. In ascending order the smallest element 1 lands at nums[0].

  2. Array.Sort call

    int[] nums = { 5, 2, 8, 1 };
    ____
    Console.WriteLine(nums[0]);
    Show answer
    int[] nums = { 5, 2, 8, 1 };
    Array.Sort(nums);
    Console.WriteLine(nums[0]);
  3. Match each method to its meaning

    Array.Sort
    Sorts ascending
    Array.Reverse
    Reverses order
    Array.IndexOf
    Finds index
    Array.Copy
    Copies elements

All lessons in Beginner