forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Ternary Search in C# (jainaman224#2176) (jainaman224#2494)
- Loading branch information
1 parent
2a067c9
commit f15adde
Showing
1 changed file
with
103 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
using System; | ||
|
||
public class ternarysrc { | ||
|
||
// Function to perform Ternary Search | ||
static int ternarySearch(int l, int r, int key, int[] ar) | ||
{ | ||
while (r >= l) | ||
{ | ||
|
||
// Finding the mid1 and mid2 | ||
int mid1 = l + (r - l) / 3; | ||
int mid2 = r - (r - l) / 3; | ||
|
||
// To check if key is present at any mid | ||
if (ar[mid1] == key) | ||
{ | ||
return mid1; | ||
} | ||
if (ar[mid2] == key) | ||
{ | ||
return mid2; | ||
} | ||
|
||
// Checking region where KEY might be present | ||
if (key < ar[mid1]) | ||
{ | ||
r = mid1 - 1; | ||
} | ||
else if (key > ar[mid2]) | ||
{ | ||
l = mid2 + 1; | ||
} | ||
else | ||
{ | ||
l = mid1 + 1; | ||
r = mid2 - 1; | ||
} | ||
} | ||
|
||
// If the KEY is not found | ||
return -1; | ||
} | ||
|
||
// Main Function to Execute | ||
public static void Main(String[] args) | ||
{ | ||
int l, r, p, i, key = 0, len = 0; | ||
|
||
// Taking the input of Array Length from user | ||
Console.WriteLine("Enter Length of Array : "); | ||
len = Convert.ToInt32(Console.ReadLine()); | ||
|
||
int[] ar = new int[len]; | ||
|
||
Console.WriteLine("Enter Array Elements in Ascending Order : "); | ||
|
||
for(i = 0; i < len; i++ ) // Array input | ||
{ | ||
ar[i] = Convert.ToInt32(Console.ReadLine()); | ||
} | ||
|
||
// Starting index | ||
l = 0; | ||
|
||
// Ending Index | ||
r = len - 1; | ||
|
||
Console.WriteLine("\nEnter the Number to be Searched : "); | ||
// KEY to be searched in the array | ||
key = Convert.ToInt32(Console.ReadLine()); | ||
|
||
// Searching the KEY using ternarySearch function | ||
p = ternarySearch(l, r, key, ar); | ||
|
||
|
||
// Checking if the KEY is present or not | ||
if(p == -1) | ||
Console.WriteLine("\nNumber Not Found"); | ||
else | ||
Console.WriteLine("\n The Index of " + key + " is " + p); | ||
Console.ReadKey(); | ||
|
||
|
||
} | ||
} | ||
|
||
// Sample Input/Output: | ||
/* | ||
Enter Length of Array : 5 | ||
Enter Array Elements in Ascending Order : | ||
10 | ||
20 | ||
30 | ||
40 | ||
50 | ||
Enter the Number to be Searched : | ||
50 | ||
The Index of 50 is 4 | ||
*/ |