常用的数据交换方法有: 1. 辅助变量法; 2. 加法运算法; 3. 异或运算法;
下面进行比较测试: - 主要比较耗时 - 比较平台为matlab
% 基本设置close allclearclca = 100; % 交换数据1b = 200; % 交换数据2c = 999999; % 交换次数% method 1a1 = a;b1 = b;tic;for i = 1 : c temp = a1; a1 = b1; b1 = temp;endtime_1 = toc;% method 2a2 = a;b2 = b;tic;for i = 1 : c a2 = a2 + b2; % 运行此步骤后,a2 = a2(原始) + b2(原始) b2 = a2 - b2; % 运行此步骤后,b2 = a2(原始) + b2(原始) - b2(原始) = a2(原始) a2 = a2 - b2; % 运行此步骤后,a2 = a2(原始) + b2(原始) - (a2(原始) + b2(原始) - b2(原始)) = b2(原始)endtime_2 = toc;% method 3% 针对16bit数据% 利用异或运算基本原理:a = a^b^b; a^b = b^aa3 = a;b3 = b;tic;for i = 1 : c a3 = bitxor(a3, b3, 'uint16'); % 运行此步骤后,a3 = a3(原始) ^ b3(原始) b3 = bitxor(a3, b3, 'uint16'); % 运行此步骤后,b3 = a3(原始) ^ b3(原始) ^ b3(原始) = a3(原始) a3 = bitxor(a3, b3, 'uint16'); % 运行此步骤后,a3 = a3(原始) ^ b3(原始) ^ (a3(原始) ^ b3(原始) ^ b3(原始)) = b3(原始)endtime_3 = toc;比较结果:
bar([time_1, time_2, time_3])xlabel('方法'), ylabel('耗时(s)')新闻热点
疑难解答