This repository was archived by the owner on Jul 18, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path05-linear_search.zig
More file actions
65 lines (55 loc) · 1.95 KB
/
Copy path05-linear_search.zig
File metadata and controls
65 lines (55 loc) · 1.95 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
const std = @import("std");
const print = std.debug.print;
const time = std.time;
const Timestamp = std.Io.Timestamp;
const allocator = std.heap.page_allocator;
/// Function to perform linear search on an array.
///
/// # Parameters
///
/// - `arr`: The array to search in.
/// - `x`: The target value to search for.
///
/// # Returns
///
/// The index of the target if found, otherwise `null`.
fn linearSearch(arr: []const usize, x: usize) ?usize {
for (0.., arr) |index, item| {
if (item == x) return index; // Element found at position index
}
return null; // Element not found
}
/// Main function to demonstrate linear search and measure execution time.
pub fn main(init: std.process.Init) !void {
const io = init.io;
const N_values = [_]usize{ 1_000_000, 2_000_000, 4_000_000, 8_000_000, 16_000_000 };
for (N_values) |N| {
// Allocate memory for the array
var arr = try allocator.alloc(usize, N);
defer allocator.free(arr);
// Fill the array with sequential elements
for (0..N) |i| {
arr[i] = i;
}
// Set the target value to be at the end of the array
// (worst case for linear search)
const target: usize = N - 1;
// Measure the start time
const start = Timestamp.now(io, .awake);
// Perform linear search
const result = linearSearch(arr[0..], target);
// Measure the end time
const end = Timestamp.now(io, .awake);
// Calculate the elapsed time in seconds
const elapsed: f64 = @floatFromInt(end.nanoseconds - start.nanoseconds);
const time_spent = elapsed / time.ns_per_s;
// Print the result and time
print("Linear Search with N = {d}\n", .{N});
if (result) |found| {
print("Target found at index {d}\n", .{found});
} else {
print("Target not found\n", .{});
}
print("Time taken: {d} seconds\n\n", .{time_spent});
}
}