-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPositionSearch.java
More file actions
executable file
·98 lines (79 loc) · 1.79 KB
/
PositionSearch.java
File metadata and controls
executable file
·98 lines (79 loc) · 1.79 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.util.Scanner;
public class PositionSearch {
public static void main(String args[])
{
/**
* Input:
* In this program we take
* n = number of integers in the array
* a[n] = n integers are inserted
* s = search element
*
* Output:
* current position of the search element
* sorted array
* new position of the search element in the sorted array
*/
Scanner in=new Scanner(System.in);
int a[]=new int[100];
int n,i,j,s ='\0',temp,count = 0;
n=in.nextInt();
for (i=0;i<n;i++)
{
a[i]=in.nextInt();
}
/**
* The label is used so that we can searchElement again if the previous searchElement was not in the array
*/
searchAgain:for (int k=0;k<=1;k++) {
s = in.nextInt();
for (i = 0; i < n; i++) {
if (s == a[i]) {
count = i + 1;
break;
}
}
if (count > 0) {
System.out.println(count);
} else {
System.out.println("Enter a search element present in the array:");
continue searchAgain;
}
}
for (i=1;i<n;i++)
{
j=i;
while(j>0&&a[j]<a[j-1])
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
j--;
}
}
for(i=0;i<n;i++)
{
System.out.print(a[i]+"\t");
}
System.out.println();
//binary search
int first=0,last=n-1,middle=(first+last)/2;
while (first<=last)
{
if(s<a[middle])
{
last=middle-1;
}
else if(s==a[middle])
{
System.out.println(middle+1);
break;
}
else
{
first=middle+1;
}
middle=(first+last)/2;
}
}
}