Selection Sort Behavioral

Here a simple Behavioral coding of the Selection Sort algorithm is given. This code is written in such a way that it can support any number of inputs with any size. This code is a basic version of the Selection sort algorithm and sorts the given array in one clock cycle. The code is written for five number of elements.

module selection_sort #(
    parameter NUM_VALS = 5,
    parameter SIZE     = 16
)(  input  wire clk,
    input  wire [NUM_VALS*SIZE-1:0] in,
    output reg  [NUM_VALS*SIZE-1:0] out
);
    reg [NUM_VALS*SIZE-1:0] sorted_bus;
    always @(posedge clk) begin
        out <= sorted_bus;
    end

    integer i, j, min_id;
    reg [SIZE-1:0] temp;
	 reg [SIZE-1:0] min;
	 
    reg [SIZE-1:0] array [1:NUM_VALS];
    always @* begin
        for (i = 0; i < NUM_VALS; i = i + 1) begin
            array[i+1] = in[i*SIZE +: SIZE];
        end

        for (i = 1; i < NUM_VALS; i = i + 1) begin
				min = array[i];
				min_id      = i;
            for (j = i + 1 ; j < NUM_VALS +1; j = j + 1) begin
                if (array[j] < min) begin
                    min         = array[j];
						  min_id      = j;
					end
					end
                    temp         = array[i];
						  array[i]     = array[min_id];
                    array[min_id] = temp;
           end
        
       for (i = 0; i < NUM_VALS; i = i + 1) begin
            sorted_bus[i*SIZE +: SIZE] = array[i+1];
       end
    end
endmodule

The test bench for this code is given below. The elements are ordered in descending order.

module selection_tb;
    reg clk;
    reg  [16-1:0] in1,  in2,  in3,  in4,  in5;
    wire [16-1:0] out1, out2, out3, out4, out5;

    selection_sort #(.NUM_VALS(5), .SIZE(16)) dut (
        .clk(clk),
        .in ({in1,  in2,  in3,  in4,  in5}),
        .out({out1, out2, out3, out4, out5})
    );

    always @(posedge clk) begin
        in1 <= random;         in2 <=random;
        in3 <= random;         in4 <=random;
        in5 <= random;     end      always @(posedge clk) begindisplay("In:  %0d %0d %0d %0d %0d", in1,  in2,  in3,  in4,  in5);
        display("Out: %0d %0d %0d %0d %0d", out1, out2, out3, out4, out5);     end      initial begin         #300;finish;
    end

    always begin
        clk = 1'b0; #5;
        clk = 1'b1; #5;
    end
endmodule

Author Description

Ardhendu Sarkar
Research Scholar
Computer Science Deptt.
IIEST, Shibpur
email: [email protected]
Ph: 9733242529

(Visited 297 times, 1 visits today)
Shopping Basket