verilog实现冒泡算法
冒泡法分为冒泡升序和冒泡降序,本次实验使用升序算法。
16个数据比较需要耗时120个时钟周期。第一轮比较,将最大数排到最后一位,耗时15个时钟周期;第二轮比较,将倒数第二大数排列到倒数第二个,耗时14个时钟周期······;最后一轮将最小数排列到第一个,耗时一个时钟周期。
verilog实现
always@(posedge clk, posedge rst)begin
if(rst) begin
comp_cnt <= 'd0;
cycle_cnt <= 'd15; end
else if(comp_flag && cycle_cnt != 'd0) begin
if(comp_cnt < cycle_cnt) begin
if(in_data[comp_cnt] > in_data[comp_cnt + 1]) begin
in_data[comp_cnt] <= in_data[comp_cnt + 1];
in_data[comp_cnt + 1] <= in_data[comp_cnt]; end
else begin
in_data[comp_cnt] <= in_data[comp_cnt];
in_data[comp_cnt + 1] <= in_data[comp_cnt + 1]; end
comp_cnt <= comp_cnt + 1'b1; end
else begin
comp_cnt <= 'd0;
cycle_cnt <= cycle_cnt - 1'b1; end
end
else begin
cycle_cnt <= cycle_cnt;
comp_cnt <= comp_cnt; end
end
仿真结果