- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are the different ways to find missing numbers in a sorted array without any inbuilt functions using C#?
There are three methods as written below −
In the first method
Use the formula n(n+1)/2 that counts the number of elements and then need to subtract from the elements in the array.
In the second method
Create a new array and traverse through the entire array and make the number false whichever is found.
In the third method
Use Xor operation. which gives the missing number.
Example
using System; namespace ConsoleApplication{ public class Arrays{ public int MissingNumber1(int[] arr){ int totalcount = 0; for (int i = 0; i < arr.Length; i++){ totalcount += arr[i]; } int count = (arr.Length * (arr.Length + 1)) / 2; return count - totalcount; } public int MissingNumber2(int[] arr){ bool[] tempArray = new bool[arr.Length + 1]; int element = -1; for (int i = 0; i < arr.Length; i++){ int index = arr[i]; tempArray[index] = true; } for (int i = 0; i < tempArray.Length; i++){ if (tempArray[i] == false){ element = i; break; } } return element; } public int MissingNumber3(int[] arr){ int result = 1; for (int i = 0; i < arr.Length; i++){ result = result ^ arr[i]; } return result; } } class Program{ static void Main(string[] args){ Arrays a = new Arrays(); int[] arr = { 0, 1, 3, 4, 5 }; Console.WriteLine(a.MissingNumber1(arr)); Console.WriteLine(a.MissingNumber2(arr)); Console.WriteLine(a.MissingNumber3(arr)); Console.ReadLine(); } } }
Output
2 2 2
Advertisements