Skip to content
Theory · Arrays · lesson 6 of 9

Sorting and searching

With a row of lockers, people usually do one of two things:

  • sort the things in it;
  • find one item.

Arrays are the same: you sort scores to see the best and the worst, and search an array to learn whether it holds a value and where. For an array, you could write either of these as a loop. But .NET has ready-made methods for them, so you do not have to write that loop.

Sorting

The method Array.Sort puts the elements of an array in ascending order, and Array.Reverse turns the array around:

C#
int[] nums = [5, 2, 9, 1];
Array.Sort(nums);
Console.WriteLine(string.Join(", ", nums)); // 1, 2, 5, 9
Array.Reverse(nums);
Console.WriteLine(string.Join(", ", nums)); // 9, 5, 2, 1

Let's go through it line by line:

  1. Array.Sort(nums) rearranges the elements so that they go in ascending order: 1, 2, 5, 9.
  2. Array.Reverse(nums) reverses the order: the first element becomes the last. After sorting, this gives descending order.

Both methods work on the same array: they move things between lockers of the same row and return nothing. They create no new array, and the old order is gone. If the array has two names, both of them show the sorted order.

Interviewers sometimes ask whether Array.Sort creates a new array. It does not: it sorts the array you pass to it.

Searching

The method Array.IndexOf looks for a value and returns the index of an element:

C#
int[] nums = [9, 5, 2, 5];
Console.WriteLine(Array.IndexOf(nums, 5)); // 1
Console.WriteLine(Array.IndexOf(nums, 7)); // -1

Array.IndexOf(nums, 5) checks the elements from the start of the array and returns the index of the first one equal to 5. There are two fives, and it finds the first, at index 1.

Array.IndexOf(nums, 7) checks all four elements and finds no seven. If the array does not hold the value, the method returns -1. There is no index -1, so this answer cannot be mistaken for the index of a found element. Before you read an element at the index IndexOf returned, check that it is not -1.

Common mistake

Someone tried to put the result of Array.Sort into a new variable:

C#
int[] nums = [5, 2, 9, 1];
int[] sorted = Array.Sort(nums); // ✗
TEXT
error CS0029: Cannot implicitly convert type 'void' to 'int[]'

The program does not compile. Array.Sort returns nothing: the message calls it void, like a method with no result. It sorts the array nums itself, so you call it as a statement of its own and then read nums. If you need the old order too, first make a real copy with a new array and Array.Copy, and then sort that copy.

Key points

  • Array.Sort and Array.Reverse rearrange the elements in the same array and return nothing.
  • Array.IndexOf returns the index of the first matching element, or -1 if there is none.