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 path09-bubble_sort.zig
More file actions
85 lines (73 loc) · 2.27 KB
/
Copy path09-bubble_sort.zig
File metadata and controls
85 lines (73 loc) · 2.27 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const std = @import("std");
const print = std.debug.print;
const time = std.time;
const Timestamp = std.Io.Timestamp;
const allocator = std.heap.page_allocator;
const Random = std.Random;
const mem = std.mem;
/// Function to perform Bubble Sort on an array.
///
/// # Parameters
///
/// - `arr`: The array to sort.
fn bubbleSort(arr: []usize) void {
const n = arr.len;
for (0..n - 1) |i| {
for (0..(n - i - 1)) |j| {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
mem.swap(usize, &arr[j], &arr[j + 1]);
}
}
}
}
/// Function to verify if an array is sorted.
///
/// # Parameters
///
/// - `arr`: The array to check.
fn isSorted(arr: []usize) bool {
const n = arr.len;
for (0..n - 1) |i| {
if (arr[i] > arr[i + 1]) {
return false;
}
}
return true;
}
/// Main function to demonstrate Bubble Sort and measure execution time.
pub fn main(init: std.process.Init) !void {
const io = init.io;
const N_values = [_]usize{ 10_000, 20_000, 30_000, 40_000 };
// Seed the random number generator
var rng = Random.DefaultPrng.init(123); // Xoshiro256 is good enough
for (N_values) |N| {
// Allocate memory for the array
var arr = try allocator.alloc(usize, N);
defer allocator.free(arr);
// Fill the array with random integers
for (0..N) |i| {
const random_value: usize = rng.next() % N;
arr[i] = random_value;
}
// Measure the start time
const start = Timestamp.now(io, .awake);
// Perform Bubble Sort
bubbleSort(arr);
// 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;
// Verify that the array is sorted
const is_sorted = isSorted(arr);
// Print the result and time
print("Bubble Sort with N = {d}\n", .{N});
if (is_sorted) {
print("Array is sorted.\n", .{});
} else {
print("Array is NOT sorted.\n", .{});
}
print("Time taken: {d} seconds\n\n", .{time_spent});
}
}