C# sorting, stability, and Array.BinarySearch

Array.Sort sorts an array in place, with an optional comparison. List<T>.Sort and Array.Sort use an introspective sort that is not stable, so equal elements may change order. LINQ's OrderBy and ThenBy are stable and return a new sequence, which makes them the right choice for sorting records by several keys.

C#
using System;
using System.Linq;

class Program {
  static void Main() {
    int[] numbers = { 5, 2, 9, 1, 5, 6 };
    Array.Sort(numbers);
    Console.WriteLine(string.Join(" ", numbers));

    int found = Array.BinarySearch(numbers, 9);
    int missing = Array.BinarySearch(numbers, 4);
    Console.WriteLine("index of 9: " + found);
    Console.WriteLine("4 would be inserted at " + ~missing);

    var people = new[] { (Name: "Ada", Age: 30), (Name: "Bo", Age: 25), (Name: "Cy", Age: 30), (Name: "Di", Age: 25) };
    var byAge = people.OrderBy(p => p.Age);
    Console.WriteLine(string.Join(",", byAge.Select(p => p.Name)));

    string[] words = { "pear", "Apple", "fig" };
    Array.Sort(words, StringComparer.OrdinalIgnoreCase);
    Console.WriteLine(string.Join(",", words));
  }
}
Read the full lesson