Array methods help you organize and find items in a list easily. Sorting arranges items, reversing flips their order, and IndexOf finds where an item is.
Array methods (Sort, Reverse, IndexOf) in C Sharp (C#)
using System; class Program { static void Main() { int[] numbers = { 5, 3, 8, 1 }; // Sort the array Array.Sort(numbers); // Reverse the array Array.Reverse(numbers); // Find index of an element int position = Array.IndexOf(numbers, 3); } }
Array.Sort(array) changes the array to be in ascending order.
Array.Reverse(array) flips the order of elements in the array.
int[] emptyArray = {}; Array.Sort(emptyArray); Array.Reverse(emptyArray); int index = Array.IndexOf(emptyArray, 10);
int[] singleElement = { 42 }; Array.Sort(singleElement); Array.Reverse(singleElement); int index = Array.IndexOf(singleElement, 42);
int[] numbers = { 10, 20, 30, 40 }; Array.Sort(numbers); // Already sorted Array.Reverse(numbers); // Now reversed int indexStart = Array.IndexOf(numbers, 40); // First element after reverse int indexEnd = Array.IndexOf(numbers, 10); // Last element after reverse
This program shows how to sort, reverse, and find the index of elements in an array. It prints the array before and after changes and shows what happens when searching for a missing item.
using System; class Program { static void Main() { int[] numbers = { 7, 2, 9, 4, 3 }; Console.WriteLine("Original array:"); PrintArray(numbers); Array.Sort(numbers); Console.WriteLine("\nAfter sorting:"); PrintArray(numbers); Array.Reverse(numbers); Console.WriteLine("\nAfter reversing:"); PrintArray(numbers); int searchValue = 4; int index = Array.IndexOf(numbers, searchValue); Console.WriteLine($"\nIndex of {searchValue}: {index}"); int missingValue = 10; int missingIndex = Array.IndexOf(numbers, missingValue); Console.WriteLine($"Index of {missingValue} (not in array): {missingIndex}"); } static void PrintArray(int[] array) { foreach (int number in array) { Console.Write(number + " "); } Console.WriteLine(); } }
Time complexity: Sort is O(n log n), Reverse is O(n), IndexOf is O(n).
Space complexity: These methods work in place, so they use little extra memory.
Common mistake: Forgetting that IndexOf returns -1 if the item is not found.
Use Sort when you need ordered data, Reverse when you want to flip order, and IndexOf to find positions.
Array.Sort arranges items in ascending order.
Array.Reverse flips the order of items in the array.
Array.IndexOf finds the position of an item or returns -1 if not found.