Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
56 lines (42 loc) · 1.67 KB

File metadata and controls

56 lines (42 loc) · 1.67 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.