Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create linear.java #167

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions linear.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Java code for linearly search x in arr[]. If x
// is present then return its location, otherwise
// return -1
class LinearSearch {
// This function returns index of element x in arr[]
static int search(int arr[], int n, int x)
{
for (int i = 0; i < n; i++) {
// Return the index of the element if the element
// is found
if (arr[i] == x)
return i;
}

// return -1 if the element is not found
return -1;
}

public static void main(String[] args)
{
int[] arr = { 3, 4, 1, 7, 5 };
int n = arr.length;

int x = 4;

int index = search(arr, n, x);
if (index == -1)
System.out.println("Element is not present in the array");
else
System.out.println("Element found at position " + index);
}
}