c# - How to refactor this routine to avoid the use of recursion? -
I was writing exercise in C # and although it Works, looking back at the code, was the place for improvement.
Basically, the second part of the algorithm to merge two sorted lists is a regular requirement.
My method is very long implementation which can use some refactoring:
Private static list & lt; Int & gt; MergeSortedLists (& lt; integer & gt; sLeft of the list, & lt; integer & gt; sRight from the list) {if (sLeft.Count == 0 || sRight.Count == 0) {sLeft.AddRange (sRight); Return SLAF; } And if (sLeft.Count == 1 & amp;;; .right.Count == 1) {If (S left [0] 1) {for (int i = 0; I & lt; sRight.Count; i ++) {if (sLeft [ 0] & lt; = sRight [i]) {SRight.Instert (i, sLeft [0]); Return sRight; }} SRight.Add (sLeft [0]); Return sRight; } Else if (sLeft.Count> 1 & amp; & amp; amp; sRight.Count == 1) {if (sRight [i = 0; I & lt; sLeft.Count; i ++) for {if (sRight [ 0] & lt; = sLeft [i]) {SLeft.Insert (i, sRight [0]); Return SLAF; }} SLeft.Add (sRight [0]); Return SLAF; } And {list & lt; Int & gt; List = new list & lt; Int & gt; (); If (sLeft [0]
Certainly this routine can be corrected / abrogated by removing recursion , etc. 2 There are other ways to merge sorted lists. Therefore, any is welcome for refactoring.
Although I have the answer, I am curious that other programmers will have to make this routine How to see improvements.
Thank you!
As a starting point, I will count your particular cases when any of the counts == 1
- Your more general (currently recurring) can be controlled by case.
if (sLeft.Count> gt;); 1 & amp; Amp; Sight.Qount == 0) Anytime will not be correct because you have checked for
sRight. Number == 0
initially - so this code will never reach and is redundant.
Finally, instead of recursive (due to the number of new lists created by you, this is very expensive in this case - a copy element!), Something like in your else
Do (in fact, it can replace your entire method):
list & lt; Int & gt; List = new list & lt; Int & gt; (); While (sLeft.Count> 0 & amp;; ;; Wright; gt; 0) {if (SLEFT [0] & lt; = sRight [0]) {list.ed (SLEFT [0]) ; SLeft.RemoveAt (0); } And {list.Add (sRight [0]); SRight.RemoveAt (0); }} // One of these two is already empty; The other is in sequential order ... list. Additional Range (sLeft); List.AddRange (sRight); Return list;
(Ideally I reapply it to use integer indexes against each list instead of using .move_clickAt
, and because It may be useful to leave the original lists intact, though it is still a more efficient code than the original!)
Comments
Post a Comment