Sort an integer array in C#
This post will discuss how to sort an integer array in C#.
1. Using Array.Sort Method
The recommended method to in-place sort an integer array is with Array.Sort method. It is overloaded to accept custom comparers, and default behavior is to sort the array in ascending order. For example,
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { int[] arr = { 1, -2, 9, 7, 5 }; Array.Sort(arr); Console.WriteLine(String.Join(", ", arr)); // -2, 1, 5, 7, 9 } } |
2. Using Enumerable.OrderBy Method
To avoid any modification to the original array, we can create a sorted copy of it. The idea is to use the LINQ’s Enumerable.OrderBy method to get a sorted sequence using the default comparer. Then, we can use the ToArray() method to get an array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; using System.Linq; public class Example { public static void Main() { int[] arr = { 1, -2, 9, 7, 5 }; int[] sortedCopy = arr.OrderBy(i => i).ToArray(); Console.WriteLine(String.Join(", ", sortedCopy)); // -2, 1, 5, 7, 9 } } |
That’s all about sorting an integer array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)