-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNextAlphaElement.java
75 lines (63 loc) · 2.03 KB
/
NextAlphaElement.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package com.datastructure;
import java.util.Scanner;
public class NextAlphaElement
{
/* Returns the smallest character from the given
set of letters that is greater than target */
static char nextGreatestAlphabet(char[] array,
char target)
{
int n = array.length;
if(target>=array[n-1])
return array[0];
int l = 0, r = array.length - 1;
int ans = -1;
// Take the first element as l and
// the rightmost element as r
while (l <= r)
{
// if this while condition does not
// satisfy simply return the first
// element.
int mid = (l + r) / 2;
if (array[mid] > target)
{
r = mid - 1;
ans = mid;
}
else
l = mid + 1;
}
// Return the smallest element
return array[ans];
}
// Driver Code
public static void main(String[] args)
{
/*
char letters[] = { 'A', 'r', 'z' };
char K = 'z';
char result = nextGreatestAlphabet(letters, K);
*/
// Function call
// System.out.println(result);
Scanner sc = new Scanner(System.in);
System.out.println("First add some characters...");
char[] array = sc.nextLine().replace(" ", "").toCharArray();
for (int i = 0; i < array.length; i++)
System.out.println(array[i]);
/*
System.out.println("\nYou have entered: "); //for-each loop to print the string
for(String str: string)
{
System.out.println(str);
}
*/
System.out.println("Enter the number to search:");
char target = sc.next().charAt(0);
System.out.println(target);
char ans = nextGreatestAlphabet(array,target);
// Function call
System.out.println("The next element is " +ans);
}
}