冒泡排序算法(C#实现) - Eric Sun - 博客园
Excerpt
简单的冒泡排序算法,代码如下://冒泡排序(从数组的起始位置开始遍历,以大数为基准:大的数向下沉一位)privatestaticvoid BubbleSortFunction(int[] array) { try { int length = array.Length; int temp; bool
简单的冒泡排序算法,代码如下:
1 | <span>//</span><span>冒泡排序(从数组的起始位置开始遍历,以大数为基准:大的数向下沉一位)</span><span><br></span><span>private</span><span>static</span><span>void</span><span> BubbleSortFunction(</span><span>int</span><span>[] array)<br> {<br> </span><span>try</span><span><br> {<br> </span><span>int</span><span> length </span><span>=</span><span> array.Length;<br> </span><span>int</span><span> temp;<br> </span><span>bool</span><span> hasExchangeAction; </span><span>//</span><span>记录此次大循环中相邻的两个数是否发生过互换(如果没有互换,则数组已经是有序的)</span><span><br></span><span><br> </span><span>for</span><span> (</span><span>int</span><span> i </span><span>=</span><span>0</span><span>; i </span><span><</span><span> length </span><span>-</span><span>1</span><span>; i</span><span>++</span><span>) </span><span>//</span><span>数组有N个数,那么用N-1次大循环就可以排完</span><span><br></span><span> {<br> hasExchangeAction </span><span>=</span><span>false</span><span>; </span><span>//</span><span>每次大循环都假设数组有序</span><span><br></span><span><br> </span><span>for</span><span> (</span><span>int</span><span> j </span><span>=</span><span>0</span><span>; j </span><span><</span><span> length </span><span>-</span><span> i </span><span>-</span><span>1</span><span>; j</span><span>++</span><span>) </span><span>//</span><span>从数组下标0处开始遍历,(length - i - 1 是刨除已经排好的大数)</span><span><br></span><span> {<br> </span><span>if</span><span> (array[j] </span><span>></span><span> array[j </span><span>+</span><span>1</span><span>]) </span><span>//</span><span>相邻两个数进行比较,如果前面的数大于后面的数,则将这相邻的两个数进行互换</span><span><br></span><span> {<br> temp </span><span>=</span><span> array[j];<br> array[j] </span><span>=</span><span> array[j </span><span>+</span><span>1</span><span>];<br> array[j </span><span>+</span><span>1</span><span>] </span><span>=</span><span> temp;<br> hasExchangeAction </span><span>=</span><span>true</span><span>; </span><span>//</span><span>发生过互换</span><span><br></span><span> }<br> }<br><br> </span><span>if</span><span> (</span><span>!</span><span>hasExchangeAction) </span><span>//</span><span>如果没有发生过互换,则数组已经是有序的了,跳出循环</span><span><br></span><span> {<br> </span><span>break</span><span>;<br> }<br> }<br> }<br> </span><span>catch</span><span> (Exception ex)<br> { }<br> }</span> |
。。。。。