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

Sign up
Appearance settings

Commit 98ddf16

Browse files
authored
Add Insertion sort Algorithm - Java
https://en.wikipedia.org/wiki/Insertion_sort Insertion sort is an algorithm that sorts a list one item at a time. The list is split into a sorted part and non-sorted part. With each iteration, it takes the next value waiting to be sorted (in the unsorted part) and it inserts it into the sorted part, into its proper location within the sorted items.
1 parent adfbcf4 commit 98ddf16

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import java.util.Arrays;
2+
3+
public class InsertionSort {
4+
5+
public static void main(String[] args) {
6+
int data[] = {52,31,25,12,48,44,38,9,37,29,43,16,22,28,41};
7+
sort(data);
8+
System.out.println(Arrays.toString(data));
9+
}
10+
11+
public static void sort(int data[]){
12+
int length = data.length;
13+
for(int i = 1; i < length; ++i){
14+
int valueInsert = data[i]; // copy of value to be inserted
15+
int indexSpace = i; // index space where item to be inserted was
16+
17+
while(indexSpace > 0 && data[indexSpace - 1] > valueInsert) {
18+
data[indexSpace] = data[indexSpace -1];
19+
indexSpace = indexSpace - 1;
20+
}
21+
data[indexSpace] = valueInsert; //located space to insert the item within sorted list
22+
}
23+
}
24+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /