diff --git a/codes/c/chapter_computational_complexity/time_complexity.c b/codes/c/chapter_computational_complexity/time_complexity.c index b8821ec6a..ee827ed14 100644 --- a/codes/c/chapter_computational_complexity/time_complexity.c +++ b/codes/c/chapter_computational_complexity/time_complexity.c @@ -56,11 +56,13 @@ int bubbleSort(int *nums, int n) { for (int i = n - 1; i > 0; i--) { // 内循环:冒泡操作 for (int j = 0; j < i; j++) { - // 交换 nums[j] 与 nums[j + 1] - int tmp = nums[j]; - nums[j] = nums[j + 1]; - nums[j + 1] = tmp; - count += 3; // 元素交换包含 3 个单元操作 + if (nums[j] > nums[j + 1]) { + // 交换 nums[j] 与 nums[j + 1] + int tmp = nums[j]; + nums[j] = nums[j + 1]; + nums[j + 1] = tmp; + count += 3; // 元素交换包含 3 个单元操作 + } } } return count; diff --git a/codes/zig/build.zig b/codes/zig/build.zig index 9584ba4b3..1a9fb0fba 100644 --- a/codes/zig/build.zig +++ b/codes/zig/build.zig @@ -5,7 +5,7 @@ const std = @import("std"); // Zig Version: 0.10.0 -// Zig Codes Build Command: zig build +// Build Command: zig build pub fn build(b: *std.build.Builder) void { const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); diff --git a/codes/zig/chapter_computational_complexity/time_complexity.zig b/codes/zig/chapter_computational_complexity/time_complexity.zig index ef8d7fe65..3b45ed79f 100644 --- a/codes/zig/chapter_computational_complexity/time_complexity.zig +++ b/codes/zig/chapter_computational_complexity/time_complexity.zig @@ -59,11 +59,13 @@ fn bubbleSort(nums: []i32) i32 { var j: usize = 0; // 内循环:冒泡操作 while (j < i) : (j += 1) { - // 交换 nums[j] 与 nums[j + 1] - var tmp = nums[j]; - nums[j] = nums[j + 1]; - nums[j + 1] = tmp; - count += 3; // 元素交换包含 3 个单元操作 + if (nums[j] > nums[j + 1]) { + // 交换 nums[j] 与 nums[j + 1] + var tmp = nums[j]; + nums[j] = nums[j + 1]; + nums[j + 1] = tmp; + count += 3; // 元素交换包含 3 个单元操作 + } } } return count;