This article will be my first post, so I would like to briefly introduce myself. Currently (2020/02/07) I am a sophomore at university and am studying information systems at the Faculty of Science and Engineering. The reason I tried to post an article was that I became strongly motivated to say, "I can't get out of a beginner forever!", So I decided to post because I thought that there would be no progress unless I changed the environment here. I searched on Google like "intermediate person" like a brain muscle, but I couldn't get good results, so I should write a lot of ** code, right? I think ** and I will write a lot of code from now on! I'm a beginner, so please understand that and watch with warm eyes lol
So the first post is a linear search. To be honest, it is appropriate why we chose linear search. Let's learn without worrying about the details.
This is an algorithm that searches for specific data (key) from the data in which a certain n data are registered. Assuming that the array contains data, we will compare the elements and keys while scanning from the beginning to the end of the array. This time, I will search for an array that has data from 1 to 9. Here's the code.
senkeitansaku.java
public class senkeitansaku {
public static void main(String[] args) {
//Create an array
int[] array = {1,2,3,4,5,6,7,8,9};
int result;
//Find an index that has 9
result = tansaku(array, 9);
//Conditional branch when the byte you want to find does not exist
if (result != -1) {
System.out.println("Found: index key = " + result);
} else {
System.out.println("Not found.");
}
}
//Define a method to search for the data you want to find
public static int tansaku(int[] array,int target) {
int notfound = -1;
for (int i=0;i<array.length;i++) {
if (array[i]==target) {
return i;
}
}return notfound;
}
}
This is my first post, so it's about this level, but I'll continue to post a lot and do my best to become a ** beginner **!