Swapping Mapped Values

polaris · · 459 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I have been playing with Golang for a few weeks now and I love it. But I recently discovered for myself something really cool!</p> <p>I look at a lot of code and see things like this..</p> <p><code> tmp := a[j] a[j] = a[i] a[i] = tmp </code> And I have even done it a few times myself but I recently learned that you can do this</p> <p><code> a[i], a[j] = a[j], a[i] </code></p> <p>I just wanted to put that trick out there and to me it made all of the difference.</p> <p>Here was a quick bubble sort I wrote implementing this swap. <a href="http://pastebin.com/pcaWFna1" rel="nofollow">http://pastebin.com/pcaWFna1</a></p> <p>My question is, is this a stable and safe thing to do. To the Go masters are there any issues with this?</p> <hr/>**评论:**<br/><br/>adonovan76: <pre><p>No, you should never implement bubble sort. ;-)</p></pre>tehbmar: <pre><p>I was on HackerRank and they wanted me to write one D:</p></pre>DeedleFake: <pre><p>Yes, it&#39;s totally fine. In fact, this is pretty much the recommended way to swap two variables. The spec states that the right-hand side of an assignment is fully evaluated before the left-hand side, so this works just fine.</p> <p>Also, to insert code into text on Reddit, or any Markdown, for that matter, either prefix each line of the code with four spaces, or surround it with backticks.</p></pre>tehbmar: <pre><p>Ah thank you I didn&#39;t know Reddit had markdown, thanks for the heads up!</p></pre>bradfitz: <pre><p>Only tangentially related, but I just recently wrote this: <a href="https://godoc.org/go4.org/reflectutil#Swapper" rel="nofollow">https://godoc.org/go4.org/reflectutil#Swapper</a></p></pre>tehbmar: <pre><p>New lines were remove so the formatting looks a little bad, sorry D:</p></pre>RalphCorderoy: <pre><p>You can also do <code>x, y = f()</code>. Study <a href="https://golang.org/ref/spec#Assignments" rel="nofollow">https://golang.org/ref/spec#Assignments</a> for enlightenment. And prefer <a href="https://en.wikipedia.org/wiki/Insertion_sort" rel="nofollow">https://en.wikipedia.org/wiki/Insertion_sort</a> over Bubble Sort for a simple method to implement. ;-)</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

459 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传