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

feat: menambahkan algoritma bubble sorting #10

Merged
merged 1 commit into from
Dec 6, 2023
Merged
Show file tree
Hide file tree
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
45 changes: 45 additions & 0 deletions algorithm/sorting/bubbleSort.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const std = @import("std");
const builtin = std.builtin;

// fungsi untuk melakukan pengurutan pada array A secara naik
pub fn bubleSorting(A: []i32) void {
var n = A.len;
while (n > 1) {
var new_n: usize = 0;
for (A[0 .. n - 1], 0..) |value, i| {
// jika nilai saat ini lebih besar dari nilai berikutnya, tukar posisi
if (value > A[i + 1]) {
std.mem.swap(i32, &A[i], &A[i + 1]);
new_n = i + 1;
}
}
n = new_n;
}
}

// testing jika array nya adalah kosong
test "array kosong" {
var array: [1]i32 = .{5};
bubleSorting(&array);
const a = array.len;
try std.testing.expect(a == 1);
try std.testing.expect(array[0] == 5);
}

// testing untuk array dengan satu elemen
test "array satu elemen" {
var array: [1]i32 = .{5};
bubleSorting(&array);
const a = array.len;
try std.testing.expect(a == 1);
try std.testing.expect(array[0] == 5);
}

// testing array yang tidak terurut
test "array tidak terurut" {
var array: [10]i32 = .{ 2, 1, 3, 4, 5, 6, 7, 9, 8, 10 };
bubleSorting(&array);
for (array, 0..) |value, i| {
try std.testing.expect(value == (i + 1));
}
}
10 changes: 10 additions & 0 deletions build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,16 @@ pub fn build(b: *std.Build) void {
.name = "faktorial.zig",
.category = "math",
});

// algoritma/sorting
// bubble sorting
if (std.mem.eql(u8, op, "algorithm/sorting/bubbleSort"))
buat_algo(b, .{
.optimize = optimize,
.target = target,
.name = "bubbleSort.zig",
.category = "algorithm/sorting",
});
}

// fungsi untuk membangun algoritma berdasarkan informasi yang diberikan
Expand Down
2 changes: 1 addition & 1 deletion runtest.sh
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ argumen='--summary all -freference-trace'
# yang sudah dibuat
$ZIG_TEST_COMMAND -Dalgoritma=math/gcd $argumen
$ZIG_TEST_COMMAND -Dalgoritma=math/faktorial $argumen

$ZIG_TEST_COMMAND -Dalgoritma=algorithm/sorting/bubbleSort $argumen