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
-
- using System;
-
- public class LinearSearcher
- {
- public static void Main()
- {
- String[] myArray = new String[7] { "kama", "dama", "lama", "yama", "pama", "rama", "lama" };
- String myString = "lama";
- Int32 myIndex;
-
-
- myIndex = Array.IndexOf(myArray, myString, 0, 6);
- Console.WriteLine($"The first occurrence of \"{myString}\" between index 0 and index 6 is at index {myIndex}.");
-
-
- myIndex = Array.LastIndexOf(myArray, myString, 6, 7);
- Console.WriteLine($"The last occurrence of \"{myString}\" between index 0 and index 6 is at index {myIndex}.");
- Console.ReadLine();
- }
- }
The program above, has this output:
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
-
-
-
-
- using System;
-
- class linSearch
- {
- public static void Main()
- {
- int[] a = new int[3];
- Console.WriteLine("Enter number of elements you want to hold in the array (max3)?");
- string s = Console.ReadLine();
- int x = Int32.Parse(s);
- Console.WriteLine("--------------------------------------------------");
- Console.WriteLine("\n Enter array elements \n");
- Console.WriteLine("--------------------------------------------------");
-
- for (int i = 0; i < x; i++)
- {
- string s1 = Console.ReadLine();
- a[i] = Int32.Parse(s1);
- }
-
- Console.WriteLine("Enter Search element\n");
- Console.WriteLine("--------------------------------------------------");
- string s3 = Console.ReadLine();
- int x2 = Int32.Parse(s3);
-
-
- Array.Sort(a);
- Console.WriteLine("--------------Sorted-------------------------");
- for (int i = 0; i < x; i++)
- {
-
- Console.WriteLine($"Element {i + 1} is {a[i]}");
- }
-
-
- int x3 = Array.BinarySearch(a, (Object)x2);
- Console.WriteLine("--------------------------------------------------");
- Console.WriteLine("Binary Search: " + x3);
- Console.WriteLine($"Element {x3} is {a[x3]}");
- Console.WriteLine("--------------------------------------------------");
-
-
- Array.Reverse(a);
- Console.WriteLine("-----------Reversed-------------------------------");
- Console.WriteLine("----------------------------------------------");
- for (int i = 0; i < x; i++)
- {
-
- Console.WriteLine($"Element {i + 1} is {a[i]}");
- }
- }
- }
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
-
- using System;
- using System.Collections;
-
- public class CompareX : IComparer
- {
- int compareFrom = 0;
- public CompareX(int i)
- {
- compareFrom = i;
- }
-
- public int Compare(object a, object b)
- {
- return String.Compare(a.ToString().Substring(compareFrom),
- b.ToString().Substring(compareFrom));
- }
- }
-
- public class ArrListEx
- {
- ArrayList arr = new ArrayList();
- public ArrListEx()
- {
- arr.Add("aaaa9999");
- arr.Add("bbbb8888");
- arr.Add("cccc7777");
- arr.Add("dddd6666");
- arr.Sort(new CompareX(4));
- IEnumerator arrList = arr.GetEnumerator();
-
- while (arrList.MoveNext())
- {
- Console.WriteLine($"Item: {arrList.Current}");
- }
- }
-
- public static void Main(string[] args)
- {
- new ArrListEx();
- }
- }
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#.