Skip to content

Commit 86aae08

Browse files
Merge pull request #23 from KodyKendall/Kody'sBranch
Create InsertionSortInteger
2 parents 86c6532 + 3e53721 commit 86aae08

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

InsertionSortInteger

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package sorts;
2+
/**
3+
* This is my implementation of an insertion sort.
4+
*
5+
* I decided to do this when i didn't feel comfortable enough about implementing
6+
* different types of sorts, so this is my trial and error to try and get myself to implement
7+
* the various sorts correctly.
8+
*
9+
* @author Kody C. Kendall
10+
*
11+
*/
12+
public class InsertionSort {
13+
14+
15+
public int[] insertionIntArraySort(int[] initialArray){
16+
17+
int[] sortedArray = new int[initialArray.length];
18+
19+
//Marking first element as sorted.
20+
sortedArray[0] = initialArray[0];
21+
22+
//For each element in the initialArray
23+
for (int index = 1; index < initialArray.length; index++){
24+
25+
//Finding the last index that was sorted
26+
int lastSortedIndex = index;
27+
28+
//Extracting the next element to be compared w/ other sorted elements from initial array
29+
int extractedElement = initialArray[index];
30+
31+
//Compare the values of the sorted index to the current extractedElement
32+
for (lastSortedIndex = index; lastSortedIndex > 0; lastSortedIndex--){
33+
34+
//If our extracted element is smaller than element to the right, switch them.
35+
if (sortedArray[lastSortedIndex-1] > extractedElement){
36+
//move the element to the left of extractedElement to the right in sortedArray
37+
sortedArray[lastSortedIndex] = sortedArray[lastSortedIndex-1];
38+
//And move the current extractedElement to the left one (since it's smaller).
39+
sortedArray[lastSortedIndex-1] = extractedElement;
40+
}
41+
else{
42+
//insert element where it is.
43+
sortedArray[lastSortedIndex] = extractedElement;
44+
//Terminating loop since element is in the right spot.
45+
break;
46+
}
47+
48+
}
49+
50+
}
51+
52+
return sortedArray;
53+
54+
}
55+
56+
}

0 commit comments

Comments
 (0)