Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First of all, you have an out-of-bounds access:</p> <pre><code> for(int j=0; j&lt;a.length; j++) { if(a[j] &gt; a[j+1]) { </code></pre> <p>for <code>j == a.length-1</code>, so the loop condition should rather be <code>j &lt; a.length-1</code>.</p> <p>But, in Bubble sort, you know that after <code>k</code> passes, the largest <code>k</code> elements are sorted at the <code>k</code> last entries of the array, so the conventional Bubble sort uses</p> <pre><code>public static void bubblesort(int[] a) { for(int i=1; i&lt;a.length; i++) { boolean is_sorted = true; for(int j=0; j &lt; a.length - i; j++) { // skip the already sorted largest elements if(a[j] &gt; a[j+1]) { int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; is_sorted = false; } } if(is_sorted) return; } } </code></pre> <p>Now, that would still do a lot of unnecessary iterations when the array has a long sorted tail of largest elements, say you have <code>k,k-1,...,1</code> as the first <code>k</code> elements and <code>k+1</code> to <code>100000000</code> in order after that. The standard Bubble sort will pass <code>k</code> times through (almost) the entire array.</p> <p>But if you remember where you made your last swap, you know that after that index, there are the largest elements in order, so</p> <pre><code>public static void bubblesort(int[] a) { int lastSwap = a.length-1; for(int i=1; i&lt;a.length; i++) { boolean is_sorted = true; int currentSwap = -1; for(int j=0; j &lt; lastSwap; j++) { if(a[j] &gt; a[j+1]) { int temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; is_sorted = false; currentSwap = j; } } if(is_sorted) return; lastSwap = currentSwap; } } </code></pre> <p>would sort the above example with only one pass through the entire array, and the remaining passes only through a (short) prefix.</p> <p>Of course, in general, that won't buy you much, but then optimising a Bubble sort is a rather futile exercise anyway.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload