Sorting, Reversing, and Searching in Arrays in C#

In this article I will explain you about Sorting, Reversing, and Searching in Arrays in C#.

You can search for the occurrence of a value in an array with the IndexOf and LastIndexOf member functions. IndexOf starts the search from a lower subscript and moves forward, and LastIndexOf starts the search from an upper subscript and moves backwards. Both functions achieve a linear search, visiting each element sequentially until they find the match forward or backward.

Listing below illustrates a linear search through an array using the IndexOf and LastIndexOf methods.

Listing: Array Linear Search

  1. // Linear Search  
  2. using System;  
  3.   
  4. public class LinearSearcher  
  5. {  
  6.     public static void Main()  
  7.     {  
  8.         String[] myArray = new String[7] { "kama""dama""lama""yama""pama""rama""lama" };  
  9.         String myString = "lama";  
  10.         Int32 myIndex;  
  11.   
  12.         // Search for the first occurrence of the duplicated value in a section of the  
  13.         myIndex = Array.IndexOf(myArray, myString, 0, 6);  
  14.         Console.WriteLine($"The first occurrence of \"{myString}\" between index 0 and index 6 is at index {myIndex}.");  
  15.   
  16.         // Search for the last occurrence of the duplicated value in a section of the  
  17.         myIndex = Array.LastIndexOf(myArray, myString, 6, 7);  
  18.         Console.WriteLine($"The last occurrence of \"{myString}\" between index 0 and index 6 is at index {myIndex}.");  
  19.         Console.ReadLine();  
  20.     }  
  21. }
The program above, has this output:

C# Linear Search

The String class provides methods for sorting, searching, and reversing that are easy to use. Note that Sort, BinarySearch, and Reverse are all static functions and are used for single-dimensional arrays.

Listing below illustrates usage of the Sort, BinarySearch, and Reverse functions.

Listing: Array Sort, Binarysearch, and Reverse Examples
  1. // Binary Search  
  2. // Note an EXCEPTION occurs if the search element is not in the list  
  3. // We leave adding this functionality as homework!  
  4.   
  5. using System;  
  6.   
  7. class linSearch  
  8. {  
  9.     public static void Main()  
  10.     {  
  11.         int[] a = new int[3];  
  12.         Console.WriteLine("Enter number of elements you want to hold in the array (max3)?");  
  13.         string s = Console.ReadLine();  
  14.         int x = Int32.Parse(s);  
  15.         Console.WriteLine("--------------------------------------------------");  
  16.         Console.WriteLine("\n Enter array elements \n");  
  17.         Console.WriteLine("--------------------------------------------------");  
  18.   
  19.         for (int i = 0; i < x; i++)  
  20.         {  
  21.             string s1 = Console.ReadLine();  
  22.             a[i] = Int32.Parse(s1);  
  23.         }  
  24.   
  25.         Console.WriteLine("Enter Search element\n");  
  26.         Console.WriteLine("--------------------------------------------------");  
  27.         string s3 = Console.ReadLine();  
  28.         int x2 = Int32.Parse(s3);  
  29.   
  30.         // Sort the values of the Array.  
  31.         Array.Sort(a);  
  32.         Console.WriteLine("--------------Sorted-------------------------");  
  33.         for (int i = 0; i < x; i++)  
  34.         {  
  35.   
  36.             Console.WriteLine($"Element {i + 1} is {a[i]}");  
  37.         }  
  38.   
  39.         // BinarySearch the values of the Array.  
  40.         int x3 = Array.BinarySearch(a, (Object)x2);  
  41.         Console.WriteLine("--------------------------------------------------");  
  42.         Console.WriteLine("Binary Search: " + x3);  
  43.         Console.WriteLine($"Element {x3} is {a[x3]}");  
  44.         Console.WriteLine("--------------------------------------------------");  
  45.   
  46.         // Reverse the values of the Array.  
  47.         Array.Reverse(a);  
  48.         Console.WriteLine("-----------Reversed-------------------------------");  
  49.         Console.WriteLine("----------------------------------------------");  
  50.         for (int i = 0; i < x; i++)  
  51.         {  
  52.   
  53.             Console.WriteLine($"Element {i + 1} is {a[i]}");  
  54.         }  
  55.     }  
  56. }  
Listing above is a more sophisticated example of using the IComparer interface and Sort function together. The IComparer interface allows you to define a Compare method in order to do a comparison between two elements of your array. This Compare method is called repeatedly by the Sort function in order to sort the array. Listing 20.15 defines a Compare method that does a comparison between two strings.

Listing: Array Sorting
  1. // sort an array according to the Nth element  
  2. using System;  
  3. using System.Collections;  
  4.   
  5. public class CompareX : IComparer  
  6. {  
  7.     int compareFrom = 0;  
  8.     public CompareX(int i)  
  9.     {  
  10.         compareFrom = i;  
  11.     }  
  12.   
  13.     public int Compare(object a, object b)  
  14.     {  
  15.         return String.Compare(a.ToString().Substring(compareFrom),  
  16.         b.ToString().Substring(compareFrom));  
  17.     }  
  18. }  
  19.   
  20. public class ArrListEx  
  21. {  
  22.     ArrayList arr = new ArrayList();  
  23.     public ArrListEx()  
  24.     {  
  25.         arr.Add("aaaa9999");  
  26.         arr.Add("bbbb8888");  
  27.         arr.Add("cccc7777");  
  28.         arr.Add("dddd6666");  
  29.         arr.Sort(new CompareX(4));  
  30.         IEnumerator arrList = arr.GetEnumerator();  
  31.   
  32.         while (arrList.MoveNext())  
  33.         {  
  34.             Console.WriteLine($"Item: {arrList.Current}");  
  35.         }  
  36.     }  
  37.   
  38.     public static void Main(string[] args)  
  39.     {  
  40.         new ArrListEx();  
  41.     }  
  42. }  
Conclusion

Hope this article would have helped you in understanding Sorting, Reversing, and Searching in Arrays in C#. See other articles on the website on .NET and C#.