# Insertion Sort in Java: Functionality, Implementation & Performance | Study.com

Tóm Tắt

## Implementation in Java

Now, let’s convert our recipe steps to an array and perform the sort. First, create a main method to store the un-sorted recipe steps and display them on screen.

`public static void main(String[] args) {  int steps = {1, 7, 9, 11, 4};  System.out.println("Before Sort: " );  for(int i = 0; i < steps.length; i++) {   System.out.println(steps[i] + ") ");  }}`

This should look like the following:

Let’s write the meat and potatoes (pun intended) of this program. We will create the following method outside of the main method, then update the main method to call the method and display the output.

`public static void sortRecipe(int sortArray[]) {  int len = sortArray.length; //start looping through the array  for(int j = 1; j < len; j++) {   //use a temp variable to keep track   int temp = sortArray[j];   //we are shifting down, so subtract 1   int i = j - 1;   //if we are at -1, we went past the beginning   //as long as j is > 0 and current bucket of the array   //is less than the temp variable, shift elements   while((j > -1) && (sortArray[i] > temp)) {    sortArray[i+1] = sortArray[i];    i--;   }    sortArray[i+1] = temp;  }}`

Next, add the following to the main method, after the original display of the un-sorted array:

`public static void sortRecipe(int sortArray[]) {  //start looping through the array  for(int i = 1; i < sortArray.length; i++) {   //start again in the array, this time   //decrementing by 1, until you've reached the beginning   //and the next element is greater than the current   for(int j = i; (j > 0 && sortArray[j-1] > sortArray[j]); j--) {    //save a temporary bucket (the ? from the graphic)    //re-sort elements so the next is greater than current    int temp = sortArray[j];    sortArray[j] = sortArray[j-1];    sortArray[j-1] = temp;   }  }}`

The algorithm begins looping through the array and then starts looping again. It will then decrement from the end, constantly checking to make sure the next element is greater than the current.

When the program runs, the following should display:

## Performance and Big-O Notation

We’ve said that an insertion sort can take additional system resources to complete. The previous sorting logic did not take an undue amount of system resources. However, think of an array that has thousands of elements. Sorting this type of array can really tax the system. Because we had a nested loop in our code, the system is going to need to process that loop early and often. How often depends on the size of the array and how out-of-order it really is.

Computer scientists use the Big-O Notation to indicate the maximum possible values a method will process. In other words, how much of a drain is this function going to be? Big-O notation is made as follows:

• O([modifier])

For example, the notation O(1) means a method/algorithm will run in the same time no matter the input or data. Think of a single line of code.

In our example, we have this notation:

• O(N

2

)

This means performance is relative to the square of the data set. As our array of recipe steps grows, so too does the processing power needed to cycle through the nested loops.

### Check the Processing Time

The following code can be added to your Java program. Add a time check before you call the sort algorithm and after. The method is nanoTime() and is accessed from the System class. You can set a benchmark time and then a stop time. The difference is how long the method took to process.

`//time checklong startTime = System.nanoTime();//call the Insertion Sort MethodsortRecipe(steps);//time checklong endTime = System.nanoTime();long totalTime = endTime - startTime;System.out.println("Time taken " + totalTime + " ns");`

To test this, we’ve changed the size the array considerably. We made the array with 500 numbers, ranging from 1 to 500, but in completely random order.

When run, the following output displayed:

Time taken 3263179 ns

This is the same as 3.26 milliseconds. It doesn’t seem like a lot of time, but think about operating systems or larger multi-tasking environments. This type of sorting could really drag down a system, especially given the complexity/size of arrays.

## Lesson Summary

An insertion sort algorithm in Java re-sorts an array by continually moving elements until they are in a numeric order. The more complex the array, the longer it will take to complete the insertion sort. Computer scientists use the Big-O Notation to indicate how much horsepower a given algorithm may take. For the insertion sort, the formula is O(N2), meaning that the time increases exponentially as the data set increases.