Skip to content

Create InsertionSortInteger #23

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 13, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions InsertionSortInteger
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package sorts;
/**
* This is my implementation of an insertion sort.
*
* I decided to do this when i didn't feel comfortable enough about implementing
* different types of sorts, so this is my trial and error to try and get myself to implement
* the various sorts correctly.
*
* @author Kody C. Kendall
*
*/
public class InsertionSort {


public int[] insertionIntArraySort(int[] initialArray){

int[] sortedArray = new int[initialArray.length];

//Marking first element as sorted.
sortedArray[0] = initialArray[0];

//For each element in the initialArray
for (int index = 1; index < initialArray.length; index++){

//Finding the last index that was sorted
int lastSortedIndex = index;

//Extracting the next element to be compared w/ other sorted elements from initial array
int extractedElement = initialArray[index];

//Compare the values of the sorted index to the current extractedElement
for (lastSortedIndex = index; lastSortedIndex > 0; lastSortedIndex--){

//If our extracted element is smaller than element to the right, switch them.
if (sortedArray[lastSortedIndex-1] > extractedElement){
//move the element to the left of extractedElement to the right in sortedArray
sortedArray[lastSortedIndex] = sortedArray[lastSortedIndex-1];
//And move the current extractedElement to the left one (since it's smaller).
sortedArray[lastSortedIndex-1] = extractedElement;
}
else{
//insert element where it is.
sortedArray[lastSortedIndex] = extractedElement;
//Terminating loop since element is in the right spot.
break;
}

}

}

return sortedArray;

}

}