module homework3 ( input clk,rst,load, input [3:0] data_in0,data_in1,data_in2,data_in3,data_in4,data_in5,data_in6,data_in7, output [3:0] data_out0,data_out1,data_out2,data_out3,data_out4,data_out5,data_out6,data_out7 ); parameter s_rst = 2'b00, s_load = 2'b01, s_sort = 2'b10, s_out = 2'b11; reg [2:0] cnt_i,turn; reg [3:0] data_fifo[0:7]; reg [1:0] cur_state,next_state; reg reset,load_data,swap; always@(posedge clk or negedge rst) begin if(!rst) cur_state <= s_rst; else cur_state <= next_state; end always@(posedge clk) begin if(reset) begin turn <= 0; cnt_i <= 0; end if(load_data) begin data_fifo[0] <= data_in0; data_fifo[1] <= data_in1; data_fifo[2] <= data_in2; data_fifo[3] <= data_in3; data_fifo[4] <= data_in4; data_fifo[5] <= data_in5; data_fifo[6] <= data_in6; data_fifo[7] <= data_in7; turn <= 7; cnt_i <= 0; end if(swap) begin if(cnt_i<turn) begin cnt_i<=cnt_i+1; if(data_fifo[cnt_i+1]<data_fifo[cnt_i]) begin data_fifo[cnt_i+1] <= data_fifo[cnt_i]; data_fifo[cnt_i ] <= data_fifo[cnt_i+1]; end end else begin cnt_i<=1; turn<=turn-1; if(data_fifo[1]<data_fifo[0]) begin data_fifo[1] <= data_fifo[0]; data_fifo[0] <= data_fifo[1]; end end end end always@(cnt_i,cur_state,turn,load) begin next_state<=s_rst; case(cur_state) s_rst: begin reset <= 1; next_state <= s_load; end s_load: begin reset<=0; if(load) begin load_data <= 1; next_state <= s_sort; end else next_state <= s_load; end s_sort: begin swap<=1; load_data<=0; if(turn== 1 && cnt_i==1) next_state<=s_out; else next_state<=s_sort; end s_out: begin next_state <= s_load; swap <= 0; end default: begin next_state<=s_rst; end endcase end assign data_out0 = data_fifo[0]; assign data_out1 = data_fifo[1]; assign data_out2 = data_fifo[2]; assign data_out3 = data_fifo[3]; assign data_out4 = data_fifo[4]; assign data_out5 = data_fifo[5]; assign data_out6 = data_fifo[6]; assign data_out7 = data_fifo[7]; endmodule