Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy sorting a randomly populated array gets progressively faster
    primarykey
    data
    text
    <p>For a programming exercise, we were told to implement insertion, selection, and bubble sorts (in java). I wanted to test how fast the sorts executed, so I wrote a loop to randomly populate and sort an array 10 times. The first two sorts take about twice as long as the last 8 iterations.. why?</p> <p>Here I have put relevant portions of code</p> <pre><code>// class fields public static final int POPULATE_MAX = 1000000000; public static final int POPULATE_MIN = -1000000000; public static void populateRandom(int[] toPopulate) { // populate array with random integers within bounds set by class fields for (int i = 0; i &lt; toPopulate.length; i++) { toPopulate[i] = (int)(Math.random() * (POPULATE_MAX - POPULATE_MIN)) + POPULATE_MIN; } } // end of method populateRandom(int[] toPopulate) public static void insertionSort(int[] toSort) throws IllegalArgumentException { if (toSort == null) { throw new IllegalArgumentException(); } if (toSort.length &lt;= 1) return; int temp; // Index i points to the next unsorted element; assigned to temp for (int i = 1; i &lt; toSort.length; i++) { temp = toSort[i]; // This loop searches through the sorted portion of the array and // determines where to put the aforementioned unsorted element for (int j = i - 1; j &gt;= 0; j--) { if (temp &lt; toSort[j]) { toSort[j + 1] = toSort[j]; if(j == 0) toSort[j] = temp; } else { toSort[j + 1] = temp; break; } // end of if (temp &lt; toSort[j]) } // end of for (int j = i - 1; j &gt;= 0; j--) } // end of for (int i = 1; i &lt; toSort.length; i++) } // end of method insertionSort(int[] toSort) throws IllegalArgumentException public static void main(String[] args) { long time; for (int testRun = 0; testRun &lt; 10; testRun++) { int[] array = new int[100000]; System.out.print(testRun + "..."); populateRandom(array); time = System.currentTimeMillis(); insertionSort(array); time = System.currentTimeMillis() - time; for (int i = 0; i &lt; array.length - 1; i++) { if (array[i] &gt; array[i+1]) System.out.println(i + ". Bad"); } System.out.println(time + " Done"); } System.out.println("ABS Done"); } </code></pre> <p>I am guessing that it has to do with branch prediction, but I am not sure as to why subsequent sorts are very noticeably faster.</p>
    singulars
    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.
 

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