Skip to content

Commit

Permalink
feat: menambahkan algoritma bubble sorting
Browse files Browse the repository at this point in the history
Signed-off-by: slowy07 <slowy.arfy@gmail.com>
  • Loading branch information
slowy07 committed Dec 6, 2023
1 parent e702254 commit 40d739b
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
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

0 comments on commit 40d739b

Please sign in to comment.