In reply to Shashank Gurijala:
I tried to infer the algorithm you are intending to use from your code. Some things don’t make sense to me. Can you please try to explain the algorithm that you intend to use here ?
This is what I would do : (there could be better ways)
- start from element 0 and walk to the end.
- [list]
- If even and non-zero → do nothing
- else if odd and zeo → do nothing
- else swap such that:: if even, swap with next non-zero element; if odd, swap with next zero element.
[/list]
Ofcourse, I assume that the input array always has a valid output available.
My implementation below :
module zero;
int i,j;
int temp;
initial begin
int array[] = {0,0,4,5,1,0,9,0,8,0};
$display("Before : The elements in the array are: %p", array);
foreach(array[i]) begin
if( (i%2 == 0) && array[i] !=0 ) continue;
else if( (i%2 == 1) && array[i] ==0 ) continue;
else swap_f(array, i, i%2);
end
$display("After : The elements in the array are: %p", array);
end
function automatic swap_f(ref int arr[], input int arr_idx, input bit odd);
if(odd) begin
for(int ii = arr_idx+1; ii < arr.size(); ii++) begin
if(arr[ii] != 0) continue;
else begin
arr[ii] = arr[arr_idx];
arr[arr_idx] = 0;
break;
end
end
end else begin //even
for(int ii = arr_idx+1; ii < arr.size(); ii++) begin
if(arr[ii] == 0) continue;
else begin
arr[arr_idx] = arr[ii];
arr[ii] = 0;
break;
end
end
end
endfunction
endmodule