Back to Repositories

Testing Linear Search Implementations in hello-algo

This test suite validates linear search implementations across both arrays and linked lists in Go, demonstrating basic search algorithm testing patterns. It covers both standard array-based and linked list-based linear search operations with specific test cases.

Test Coverage Overview

The test suite provides comprehensive coverage of linear search functionality in two distinct data structures.

Key areas tested include:
  • Array-based linear search implementation
  • Linked list-based linear search implementation
  • Target element location verification
  • Index retrieval validation

Implementation Analysis

The testing approach employs Go’s native testing framework with direct function calls and output validation. It utilizes a dual-testing strategy examining both array and linked list implementations simultaneously, leveraging Go’s testing.T struct for test execution.

Technical patterns include:
  • Direct test case definition with predetermined input data
  • Parallel testing of different data structure implementations
  • Output verification through fmt.Println for visual confirmation

Technical Details

Testing infrastructure includes:
  • Go testing package (testing)
  • Custom package imports from hello-algo/pkg
  • ArrayToLinkedList utility function
  • fmt package for output formatting

Best Practices Demonstrated

The test implementation showcases several testing best practices in Go.

Notable practices include:
  • Clear test function naming convention
  • Structured test data preparation
  • Multiple implementation testing in single test function
  • Consistent variable naming and documentation

krahets/hello-algo

codes/go/chapter_searching/linear_search_test.go

            
// File: linear_search_test.go
// Created Time: 2022-11-25
// Author: Reanon ([email protected])

package chapter_searching

import (
	"fmt"
	"testing"

	. "github.com/krahets/hello-algo/pkg"
)

func TestLinearSearch(t *testing.T) {
	target := 3
	nums := []int{1, 5, 3, 2, 4, 7, 5, 9, 10, 8}

	// 在数组中执行线性查找
	index := linearSearchArray(nums, target)
	fmt.Println("目标元素 3 的索引 =", index)

	// 在链表中执行线性查找
	head := ArrayToLinkedList(nums)
	node := linearSearchLinkedList(head, target)
	fmt.Println("目标节点值 3 的对应节点对象为", node)
}