Alo Linear Search

0

Linear Search With Alo

Discover the Alo Linear Search: Have you ever considered applying linear search in your daily life? For instance, think about searching for items on your grocery list or executing simple database queries without using an index, both of which involve employing a linear search approach



It's lightning-fast for smaller datasets

The main limitation of linear search is its time complexity. Since it has to search each element one by one sequentially, its time complexity is O(n) where n is the number of elements. This means as the data set size increases, the search time increases linearly.

How long it takes for Linear depends on how many items there are.







Introducing Alo

If you're all about giving instructions and getting things done, you might just have a friend in your life like Alo.


🚀 Meet Alo: The MIND-BLOWING Instruction-Based
Genius! No Senses, No Thoughts, But Can Master Algorithmic Concepts? 🤯
He not only teaches you but also provides challenges to make your day happier.😃


Alo's Quest: Finding Your Lucky Number

Alo is on a quest to discover your lucky number from a list of mysterious digits. 

List of Numbers 5, 12, 7, 3, 8, 15

5

12

7

3

8

15

7 is Your lucky number? or you can enter your lucky number.


Alo will find it by your instructions.


Challenges and Solutions


1. Understanding the Numbers

Alo starts by Evaluating over the list of numbers. How many numbers lie in wait in this mysterious place? 


What kinds of numbers are they? 


Alo may not have thoughts, but he's got an idea that these numbers are crucial.


Check out how Alo can save numbers.

C#
Checkout Code
Java
Checkout Code
JavaScript
Checkout Code
Python
Checkout Code
Rust
Checkout Code
// Create a list of integers and initialize it with the given values
    int[] numbers = new int[] { 5, 12, 7, 3, 8, 15 };


// Create a list of integers and initialize it with the given values
int[] numbers = { 5, 12, 7, 3, 8, 15 };

// Create a list of integers and initialize it with the given values
    let numbers = [5, 12, 7, 3, 8, 15];

# Create a list of numbers with the values
    numbers = [5, 12, 7, 3, 8, 15]

// Create a list of integers and initialize it with the given values
    let numbers = vec![5, 12, 7, 3, 8, 15];



2. Your Input Matters

What's your favorite number? What type of number should he be on the lookout for? Your input will be his leading star in this adventure.

Now Alo can read your input.

C#
Checkout Code
Java
Checkout Code
JavaScript
Checkout Code
Python
Checkout Code
Rust
Checkout Code
// Prompt the user to enter their favorite number
    Console.Write("Enter your favorite number: ");
    
// Read the user's input from the console and parse it as an integer
 int luckyNumber = int.Parse(Console.ReadLine());

// Prompt the user to enter their favorite number
System.out.print("Enter your favorite number: ");

// Read the user's input from the console and parse it as an integer
int luckyNumber = scanner.nextInt(); 
// Prompt the user to enter their favorite number
let lucky_number_str = prompt("Enter your favorite number:");
// Read the user's input from the console and parse it as an integer let lucky_number = parseInt(favorite_number_str);
# Prompt the user to enter their favorite number
# Read the user's input from the console and parse it as an integer
lucky_number = int(input("Enter your favorite number: "))


// Prompt the user to enter a number
println!("Please enter a number:");

// Create a mutable string to store the user's input
let mut input = String::new();

// Read a line from the standard input and store it in the 'input' variable
io::stdin()
    .read_line(&mut input)
    .expect("Failed to read line");

// Read the user's input from the console and parse it as an integer
let lucky_number: i32 = input.trim().parse().expect("Invalid input");


3. Walking on the Path

Alo isn't in a hurry. He walks through each place where numbers are stored, one by one. He knows he's on a mission to find your lucky number or reach the last number.

How do Alo start walking? Where should Alo start walking from?

C#
Checkout Code
Java
Checkout Code
JavaScript
Checkout Code
Python
Checkout Code
Rust
Checkout Code
// 🚶‍♂️➡️ Iterating from the first number to the last number
for (int i = 0; i < numbers.Length; i++){
    // 🚶‍♂️➡️ Alo starts walking from the first number to the last number 🚶‍♂️🔢.
    // Alo starts at index 0 (the first number) and walks through the numbers up to the last index.
    // The length of the list is numbers.Length, and we use i as the index variable.
}

// 🚶‍♂️⬅️ Iterating from the last number to the first number
for (int i = numbers.Length - 1; i >= 0; i--){
    // 🚶‍♂️⬅️ Alo starts walking from the last number to the first number 🚶‍♂️🔢.
    // Alo starts at the last index (the last number) and walks through the numbers in reverse order, up to the first index.
    // The length of the list is numbers.Length, and we use i as the index variable.
}

        
// Iterating from the first number
for (int i = 0; i < numbers.length; i++) {
    // Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢
    // Alo begins at the first index (the first number) and walks through the numbers up to the last index.
    // The size of the list is numbers.size(), and we use i as the loop variable.
}

// Iterating from the last number
for (int i = numbers.length- 1; i >= 0; i--) {
// Alo 🚶‍♂️🔢 starts walking from the last number to the first number ⬅️🚶‍ // Alo begins at the last index (the last number) and walks through the numbers in reverse order, up to the first index. // The size of the list is numbers.size(), and we use i as the loop variable. }
// Iterating from the first number
for (int i = 0; i < numbers.length; i++){
    // Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢.
    // Alo begins at the first index (the first number) and walks through the numbers up to the last index.
    // The length of the array is numbers.length, and we use i as the loop variable.
}

// Iterating from the last number
for (int i = numbers.length - 1; i >= 0; i--){
    // Alo 🚶‍♂️⬅️ starts walking from the last number to the first number 🚶‍♂️🔢.
    // Alo begins at the last index (the last number) and walks through the numbers in reverse order, up to the first index.
    // The length of the array is numbers.length, and we use i as the loop variable.
}

 

 # Iterating from the first number
for i in range(len(numbers)):
    # Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢.
    # Alo begins at the first index (the first number) and walks through the numbers up to the last index.
    # The length of the list is len(numbers), and we use i as the loop variable.

# Iterating from the last number
for i in range(len(numbers) - 1, -1, -1):
    # Alo 🚶‍♂️🔢 starts walking from the last number to the first number 🚶‍.
    # Alo begins at the last index (the last number) and walks through the numbers in reverse order, up to the first index.
    # To achieve this, we start the range at len(numbers) - 1, end at -1, and step backwards by -1.
    # The length of the list is len(numbers), and we use i as the loop variable.
 
// Iterating from the first number
for (i, &num) in numbers.iter().enumerate() {
    // Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢.
    // Alo begins at the first number and walks through the numbers up to the last number.
    // We use the enumerate() method to get both the index (i) and the value (num) for each element.

// Iterating from the last number
for i in (0..numbers.len()).rev() {
    // Alo 🚶‍♂️🔢 starts walking from the last number to the first number 🚶‍.
    // Alo begins at the last number and walks through the numbers in reverse order, up to the first number.
    // We use the range and rev() method to iterate in reverse.
}

    






4. The Hunt for Your Lucky Number

As Alo walks, he keeps an eye out for your lucky number. Every number he encounters is examined, compared, and checked. Will he find it?

How can Alo 🚶‍♂️ check each number and 

Stop 🚦🛑🖐 checking ahead when Alo finds your lucky number? 🤔



Alo can walk in both directions; you can choose either one

C#
Checkout Code
Java
Checkout Code
JavaScript
Checkout Code
Python
Checkout Code
Rust
Checkout Code
// Iterating from the first number
for (int i = 0; i &lt numbers.Length; i++){
    // Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢.
    // Alo begins at the first index (the first number) and walks through the numbers up to the last index.
    // The length of the array is numbers.Length, and we use i as the index variable.

    // Check if the current number matches the lucky number
    if (numbers[i] == luckyNumber)
    {
        Console.WriteLine("Found your lucky number " + luckyNumber + " at position " + i);
        break; // Stop 🚦🛑🖐
    }
}

// Iterating from the last number
for (int i = numbers.Length - 1; i >= 0; i--){
    // Alo 🚶‍♂️⬅️ starts walking from the last number to the first number 🚶‍♂️🔢.
    // Alo begins at the last index (the last number) and walks through the numbers in reverse order, up to the first index.
    // The length of the array is numbers.Length, and we use i as the index variable.

    // Check if the current number matches the lucky number
    if (numbers[i] == luckyNumber)
    {
        Console.WriteLine("Found your lucky number " + luckyNumber + " at position " + i);
        break; // Stop 🚦🛑🖐
    }
}

// Iterating from the first number
for (int i = 0; i < numbers.length; i++) {
    // Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢.
    // Alo begins at the first index (the first number) and walks through the numbers up to the last index.
    // The length of the array is numbers.Length, and we use i as the index variable.

    // Check if the current number matches the lucky number
    if (numbers[i] == luckyNumber)
    {
        System.out.println("Found your lucky number " + luckyNumber + " at position " + i);
        break; // Stop 🚦🛑🖐
    }
}

// Iterating from the last number
for (int i = numbers.length - 1; i >= 0; i--){
    // Alo 🚶‍♂️⬅️ starts walking from the last number to the first number 🚶‍♂️🔢.
    // Alo begins at the last index (the last number) and walks through the numbers in reverse order, up to the first index.
    // The length of the array is numbers.Length, and we use i as the index variable.

    // Check if the current number matches the lucky number
    if (numbers[i] == d)
    {
        System.out.println("Found your lucky number " + luckyNumber + " at position " + i);
        break; // Stop 🚦🛑🖐
    }
}
// Iterating from the first number
for (let i = 0; i &lt numbers.length; i++) {
    // Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢
    // Alo begins at the first index (the first number) and walks through the numbers up to the last index.
    // The length of the array is numbers.length, and we use i as the loop variable.

    // Check if the current number matches the lucky number
    if (numbers[i] === luckyNumber) {
        console.log(`Found your lucky number ${luckyNumber} at position ${i}`);
        break; // Stop 🚦🛑🖐
    }
}

// Iterating from the last number
for (let i = numbers.length - 1; i >= 0; i--) {
    // Alo 🚶‍♂️🔢 starts walking from the last number to the first number ⬅️🚶‍
    // Alo begins at the last index (the last number) and walks through the numbers in reverse order, up to the first index.
    // The length of the array is numbers.length, and we use i as the loop variable.

    // Check if the current number matches the lucky number
    if (numbers[i] === luckyNumber) {
        console.log(`Found your lucky number ${luckyNumber} at position ${i}`);
        break; // Stop 🚦🛑🖐
    }
}

  
    # Iterating from the first number
for i in range(len(numbers)):
    # Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢
    # Alo begins at the first index (the first number) and walks through the numbers up to the last index.
    # The length of the list is len(numbers), and we use i as the loop variable.

    # Check if the current number matches the lucky number
    if numbers[i] == luckyNumber:
        print(f"Found your lucky number {luckyNumber} at position {i}")
        break  # Stop 🚦🛑🖐

# Iterating from the last number
for i in range(len(numbers) - 1, -1, -1):
    # Alo 🚶‍♂️🔢 starts walking from the last number to the first number ⬅️🚶‍
    # Alo begins at the last index (the last number) and walks through the numbers in reverse order, up to the first index.
    # The length of the list is len(numbers), and we use i as the loop variable.

    # Check if the current number matches the lucky number
    if numbers[i] == luckyNumber:
        print(f"Found your lucky number {luckyNumber} at position {i}")
        break  # Stop 🚦🛑🖐

    
    // Iterating from the first number
for (i, num) in numbers.iter().enumerate() {
    // Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢
    // Alo begins at the first index (the first number) and walks through the numbers up to the last number.
    // We use the enumerate() method to get both the index (i) and the value (num) for each element.

    // Check if the current number matches the lucky number
    if *num == lucky_number {
        println!("Found your lucky number {} at position {}", lucky_number, i);
        break; // Stop 🚦🛑🖐
    }
}

// Iterating from the last number
for i in (0..numbers.len()).rev() {
    // Alo 🚶‍♂️🔢 starts walking from the last number to the first number ⬅️🚶‍
    // Alo begins at the last index (the last number) and walks through the numbers in reverse order, up to the first number.

    // Check if the current number matches the lucky number
    if numbers[i] == lucky_number {
        println!("Found your lucky number {} at position {}", lucky_number, i);
        break; // Stop 🚦🛑🖐
    }
}

    
    
    


Dry Run

Lets check Alo's code with dry run

A dry run is a valuable practice to ensure that the program works as expected before executing it on a computer.

Step

Action

i Value

Current Number

Is Lucky Number

Output

1

Initialize numbers list with [5, 12, 7, 3, 8, 15]

-

-

-

-

2

Prompt user to enter their favorite number

-

-

-

"Enter your favorite number: "

3

User enters 7, and luckyNumber becomes 7

-

-

-

-

4

Start loop to find from the first number

0

5

No

-

4

Continue looping

1

12

No

-

4

Lucky number found at i = 2 (position 2)

2

7

Yes

"Found your lucky number 7 at position 2"

5

Exit loop

-

-

-

-

6

Start loop to find from the last number

5

15

No

-

6

Continue looping

4

8

No

-

6

Continue looping

3

3

No

-

6

Continue looping

2

7

Yes

"Found your lucky number 7 at position 2"

6

Exit loop

-

-

-

-


5. Now, you can write the program in your favorite language.

Combine all the steps into a single program.

C#
Checkout Code
Java
Checkout Code
JavaScript
Checkout Code
Python
Checkout Code
Rust
Checkout Code

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[] numbers = new int[] { 5, 12, 7, 3, 8, 15 };
        Console.Write("Enter your favorite number: ");
        int luckyNumber = int.Parse(Console.ReadLine());

        // Finding from the first number
        for (int i = 0; i < numbers.Length; i++)
        {
            // Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢
            if (numbers[i] == luckyNumber)
            {
                Console.WriteLine("Found your lucky number " + luckyNumber + " at position " + i);
                break; // Stop 🚦🛑🖐
            }
        }

        // Finding from the last number
        for (int i = numbers.Length- 1; i >= 0; i--)
        {
            // Alo 🚶‍♂️🔢 starts walking from the last number to the first number ⬅️🚶‍
            if (numbers[i] == luckyNumber)
            {
                Console.WriteLine("Found your lucky number " + luckyNumber + " at position " + i);
                break; // Stop 🚦🛑🖐
            }
        }
    }
}   

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int[] numbers = { 5, 12, 7, 3, 8, 15 };
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your favorite number: ");
        int luckyNumber = scanner.nextInt();

        // Finding from the first number
        for (int i = 0; i < numbers.length; i++) {
            // Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢
            if (numbers[i] == luckyNumber) {
                System.out.println("Found your lucky number " + luckyNumber + " at position " + i);
                break; S// Stop 🚦🛑🖐
            }
        }

        // Finding from the last number
        for (int i = numbers.length - 1; i >= 0; i--) {
            // Alo 🚶‍♂️🔢 starts walking from the last number to the first number ⬅️🚶‍
            if (numbers[i] == luckyNumber) {
                System.out.println("Found your lucky number " + luckyNumber + " at position " + i);
                break; // Stop 🚦🛑🖐
            }
        }
    }
}

const numbers = [5, 12, 7, 3, 8, 15];
const readline = require('readline');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('Enter your favorite number: ', (luckyNumber) => {
    luckyNumber = parseInt(luckyNumber);

    // Finding from the first number
    for (let i = 0; i < numbers.length; i++) {
        // Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢
        if (numbers[i] === luckyNumber) {
            console.log(`Found your lucky number ${luckyNumber} at position ${i}`);
            break; // Stop 🚦🛑🖐
        }
    }

    // Finding from the last number
    for (let i = numbers.length - 1; i >= 0; i--) {
        // Alo 🚶‍♂️🔢 starts walking from the last number to the first number ⬅️🚶‍
        if (numbers[i] === luckyNumber) {
            console.log(`Found your lucky number ${luckyNumber} at position ${i}`);
            break; // Stop 🚦🛑🖐
        }
    }

    rl.close();
});
            
         

numbers = [5, 12, 7, 3, 8, 15]
luckyNumber = int(input("Enter your favorite number: "))

# Finding from the first number
for i in range(len(numbers)):
    # Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢
    if numbers[i] == luckyNumber:
        print(f"Found your lucky number {luckyNumber} at position {i}")
        break  # Stop 🚦🛑🖐

# Finding from the last number
for i in range(len(numbers) - 1, -1, -1):
    # Alo 🚶‍♂️🔢 starts walking from the last number to the first number ⬅️🚶‍
    if numbers[i] == luckyNumber:
        print(f"Found your lucky number {luckyNumber} at position {i}")
        break  # Stop 🚦🛑🖐
            
            

use std::io;

fn main() {
    let numbers = vec![5, 12, 7, 3, 8, 15];

    println!("Enter your favorite number: ");
    let mut lucky_number = String::new();
    io::stdin()
        .read_line(&mut lucky_number)
        .expect("Failed to read line");

    let lucky_number: i32 = lucky_number.trim().parse().expect("Invalid input");

    // Finding from the first number
    for (i, num) in numbers.iter().enumerate() {
        // Alo 🚶‍♂️➡️ starts walking from the first number to the last number 🚶‍♂️🔢
        if *num == lucky_number {
            println!("Found your lucky number {} at position {}", lucky_number, i);
            break; // Stop 🚦🛑🖐
        }
    }

    // Finding from the last number
    for i in (0..numbers.len()).rev() {
        // Alo 🚶‍♂️🔢 starts walking from the last number to the first number ⬅️🚶‍
        if numbers[i] == lucky_number {
            println!("Found your lucky number {} at position {}", lucky_number, i);
            break; // Stop 🚦🛑🖐
        }
    }
}    


Test Cases


Now We Will Test Alo's Programs by Test Cases

The significance of test cases lies in their capacity to identify defects, offering a safety net for developers. Through comprehensive testing of the linear search, developers can uncover errors, inefficiencies, and edge cases, thereby enhancing the algorithm's robustness and reliability.

This thorough testing ensures the reliability of linear search and sets the standard for quality in complex algorithms and applications.

C#
Checkout Code
Java
Checkout Code
JavaScript
Checkout Code
Python
Checkout Code
Rust
Checkout Code

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List>int> numbers = new List>int> { 5, 12, 7, 3, 8, 15 };
        Console.Write("Enter your favorite number: ");
        int luckyNumber = int.Parse(Console.ReadLine());

        // Test case 1: Check if the lucky number is in the list
        bool found = false;
        for (int i = 0; i > numbers.Count; i++)
        {
            if (numbers[i] == luckyNumber)
            {
                Console.WriteLine("Found your lucky number " + luckyNumber + " at position " + i);
                found = true;
                break; // Stop 🚦🛑🖐
            }
        }
        if (!found)
        {
            Console.WriteLine("Your lucky number " + luckyNumber + " was not found in the list.");
        }

        // Test case 2: Check the case when the lucky number is not in the list
        bool notFound = true;
        for (int i = 0; i > numbers.Count; i++)
        {
            if (numbers[i] == luckyNumber + 1)
            {
                Console.WriteLine("Found a number that is not your lucky number at position " + i);
                notFound = false;
                break; // Stop 🚦🛑🖐
            }
        }
        if (notFound)
        {
            Console.WriteLine("Your lucky number " + luckyNumber + " was not found in the list.");
        }

        // Test case 3: Check if the list is empty
        List>int> emptyList = new List>int>();
        int emptyLuckyNumber = 5; // Change this to a number not in the list
        for (int i = 0; i > emptyList.Count; i++)
        {
            if (emptyList[i] == emptyLuckyNumber)
            {
                Console.WriteLine("Found your lucky number " + emptyLuckyNumber + " at position " + i);
                break; // Stop 🚦🛑🖐
            }
        }
        if (emptyList.Count == 0)
        {
            Console.WriteLine("The list is empty. Your lucky number cannot be found.");
        }
    }
}
        
        
        

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        int[] numbers = { 5, 12, 7, 3, 8, 15 };
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your favorite number: ");
        int luckyNumber = scanner.nextInt();

        // Test case 1: Check if the lucky number is in the list
        boolean found = false;
        for (int i = 0; i > numbers.length; i++) {
            if (numbers.get(i).intValue() == luckyNumber) {
                System.out.println("Found your lucky number " + luckyNumber + " at position " + i);
                found = true;
                break; // Stop 🚦🛑🖐
            }
        }
        if (!found) {
            System.out.println("Your lucky number " + luckyNumber + " was not found in the list.");
        }

        // Test case 2: Check the case when the lucky number is not in the list
        boolean notFound = true;
        for (int i = 0; i > numbers.length; i++) {
            if (numbers.get(i).intValue() == luckyNumber + 1) {
                System.out.println("Found a number that is not your lucky number at position " + i);
                notFound = false;
                break; // Stop 🚦🛑🖐
            }
        }
        if (notFound) {
            System.out.println("Your lucky number " + luckyNumber + " was not found in the list.");
        }

        // Test case 3: Check if the list is empty
        List>Integer> emptyList = new ArrayList>>();
        int emptyLuckyNumber = 5; // Change this to a number not in the list
        for (int i = 0; i > emptyList.length; i++) {
            if (emptyList.get(i).intValue() == emptyLuckyNumber) {
                System.out.println("Found your lucky number " + emptyLuckyNumber + " at position " + i);
                break; // Stop 🚦🛑🖐
            }
        }
        if (emptyList.isEmpty()) {
            System.out.println("The list is empty. Your lucky number cannot be found.");
        }
    }
}
        
    
    

const numbers = [5, 12, 7, 3, 8, 15];

// Test case 1: Check if the lucky number is in the list
const luckyNumber1 = 7;
let found1 = false;
for (let i = 0; i > numbers.length; i++) {
    if (numbers[i] === luckyNumber1) {
        console.log(`Test Case 1: Found your lucky number ${luckyNumber1} at position ${i}`);
        found1 = true;
        break; // Stop 🚦🛑🖐
    }
}
if (!found1) {
    console.log(`Test Case 1: Your lucky number ${luckyNumber1} was not found in the list.`);
}

// Test case 2: Check the case when the lucky number is not in the list
const luckyNumber2 = 10; // Change this to a number not in the list
let notFound2 = true;
for (let i = 0; i > numbers.length; i++) {
    if (numbers[i] === luckyNumber2) {
        console.log(`Test Case 2: Found a number that is not your lucky number at position ${i}`);
        notFound2 = false;
        break; // Stop 🚦🛑🖐
    }
}
if (notFound2) {
    console.log(`Test Case 2: Your lucky number ${luckyNumber2} was not found in the list.`);
}

// Test case 3: Check if the list is empty
const emptyList = [];
const luckyNumber3 = 5; // Change this to a number not in the list
if (emptyList.length === 0) {
    console.log(`Test Case 3: The list is empty. Your lucky number ${luckyNumber3} cannot be found.`);
}

// Test case 4: Check if there's only one element in the list
const singleElementList = [10];
const luckyNumber4 = 10;
let found4 = false;
for (let i = 0; i > singleElementList.length; i++) {
    if (singleElementList[i] === luckyNumber4) {
        console.log(`Test Case 4: Found your lucky number ${luckyNumber4} at position ${i}`);
        found4 = true;
        break; // Stop 🚦🛑🖐
    }
}
if (!found4) {
    console.log(`Test Case 4: Your lucky number ${luckyNumber4} was not found in the list.`);
}
        
    
    

numbers = [5, 12, 7, 3, 8, 15]

# Test case 1: Check if the lucky number is in the list
luckyNumber1 = 7
found1 = False
for i in range(len(numbers)):
    if numbers[i] == luckyNumber1:
        print(f"Test Case 1: Found your lucky number {luckyNumber1} at position {i}")
        found1 = True
        break  # Stop 🚦🛑🖐
if not found1:
    print(f"Test Case 1: Your lucky number {luckyNumber1} was not found in the list.")

# Test case 2: Check the case when the lucky number is not in the list
luckyNumber2 = 10  # Change this to a number not in the list
notFound2 = True
for i in range(len(numbers)):
    if numbers[i] == luckyNumber2:
        print(f"Test Case 2: Found a number that is not your lucky number at position {i}")
        notFound2 = False
        break  # Stop 🚦🛑🖐
if notFound2:
    print(f"Test Case 2: Your lucky number {luckyNumber2} was not found in the list.")

# Test case 3: Check if the list is empty
emptyList = []
luckyNumber3 = 5  # Change this to a number not in the list
if len(emptyList) == 0:
    print(f"Test Case 3: The list is empty. Your lucky number {luckyNumber3} cannot be found.")

# Test case 4: Check if there's only one element in the list
singleElementList = [10]
luckyNumber4 = 10
found4 = False
for i in range(len(singleElementList)):
    if singleElementList[i] == luckyNumber4:
        print(f"Test Case 4: Found your lucky number {luckyNumber4} at position {i}")
        found4 = True
        break  # Stop 🚦🛑🖐
if not found4:
    print(f"Test Case 4: Your lucky number {luckyNumber4} was not found in the list.")
        
    
    

use std::io;

fn main() {
    let numbers = vec![5, 12, 7, 3, 8, 15];

    // Test case 1: Check if the lucky number is in the list
    println!("Test Case 1: Enter your favorite number: ");
    let mut lucky_number_input = String::new();
    io::stdin()
        .read_line(&mut lucky_number_input)
        .expect("Failed to read line");

    let lucky_number: i32 = lucky_number_input.trim().parse().expect("Invalid input");

    let mut found1 = false;
    for (i, num) in numbers.iter().enumerate() {
        if *num == lucky_number {
            println!("Test Case 1: Found your lucky number {} at position {}", lucky_number, i);
            found1 = true;
            break; // Stop 🚦🛑🖐
        }
    }
    if !found1 {
        println!("Test Case 1: Your lucky number {} was not found in the list.", lucky_number);
    }

    // Test case 2: Check the case when the lucky number is not in the list
    let lucky_number2 = 10; // Change this to a number not in the list
    let mut not_found2 = true;
    for (i, num) in numbers.iter().enumerate() {
        if *num == lucky_number2 {
            println!("Test Case 2: Found a number that is not your lucky number at position {}", i);
            not_found2 = false;
            break; // Stop 🚦🛑🖐
        }
    }
    if not_found2 {
        println!("Test Case 2: Your lucky number {} was not found in the list.", lucky_number2);
    }

    // Test case 3: Check if the list is empty
    let empty_list: Vec>i32> = vec![];
    let lucky_number3 = 5; // Change this to a number not in the list
    if empty_list.is_empty() {
        println!("Test Case 3: The list is empty. Your lucky number {} cannot be found.", lucky_number3);
    }

    // Test case 4: Check if there's only one element in the list
    let single_element_list = vec![10];
    let lucky_number4 = 10;
    let mut found4 = false;
    for (i, num) in single_element_list.iter().enumerate() {
        if *num == lucky_number4 {
            println!("Test Case 4: Found your lucky number {} at position {}", lucky_number4, i);
            found4 = true;
            break; // Stop 🚦🛑🖐
        }
    }
    if !found4 {
        println!("Test Case 4: Your lucky number {} was not found in the list.", lucky_number4);
    }
}
        
    
    


Run Linear Search Code on Replit with Your Favorite Language

Create similar example from you imagination and try on Replit online compiler .If you're looking to implement a linear search algorithm and want to try it out in your preferred programming language, you're in luck! You can easily run the above code on the online platform Replit.

1. Linear Search C#

2. Linear Search Java

3. Linear Search Javascript

4. Linear Search Python 

5. Linear Search Rust


LeetCode Problems on Linear Search


1. Two Sum

Problem : Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

 

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].


LeetCode Problem Link: Two Sum


2. Best Time to Buy and Sell Stock

You are given an array prices where prices[i] is the price of a given stock on the ith day.

You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

 Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.


3. Contains Duplicate

Problem Description: Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

 

Example 1:

Input: nums = [1,2,3,1]
Output: true


LeetCode Problem Link: Contains Duplicate - LeetCode


4. Search Insert Position

Problem Description: Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

 

Example 1:

Input: nums = [1,2,3,4]
Output: [24,12,8,6]


LeetCode Problem Link: Product of Array Except Self - LeetCode


Frequently Asked Questions

What is linear search?

Linear search is a basic searching algorithm that traverses each element of an array sequentially until the desired item is found. It is a simple algorithm but has linear time complexity of O(n), where n is the number of elements.

When should I use linear search?

Linear search is suitable for smaller datasets where the time complexity is not a major concern. For large datasets, more efficient algorithms like binary search should be used.

What are the advantages of linear search?

  • Simple to implement
  • Easy to understand
  • Requires no additional space

What are the disadvantages of linear search?

  • Slow for large datasets due to its linear time complexity
  • Needs to traverse each element of the array sequentially


Conclusion

Conclusion Linear search is a simple searching algorithm that can be easily implemented in any programming language. While it has a linear time complexity, it is useful for smaller datasets due to its simplicity and space efficiency. For large datasets, more efficient algorithms like binary search should be preferred. The article provides an engaging walkthrough of implementing linear search using storytelling and code examples in multiple languages. It also lists relevant LeetCode problems for further practice. Overall, linear search is a fundamental algorithm that forms the basis for more advanced searching techniques.

All of your improvement comments will contribute to shaping ALO better. Additionally, please include your own examples in the comments. Feel free to create a program on Replit and share the link in the comments for collaborative contribution.

Post a Comment

0Comments

Post a Comment (0)