Skip to content

Commit 4cfa033

Browse files
committed
Added insertion sort as part of the sorting algorithms series e02 - Easy
1 parent 27d902c commit 4cfa033

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
Time:
3+
Best = O(n), Average = O(n^2), Worst = O(n^2)
4+
Space: O(1)
5+
*/
6+
class Solution {
7+
public int[] sortArray(int[] nums) {
8+
// The very first number by itself is sorted
9+
for (int i = 0; i < nums.length; i++) {
10+
int j = i;
11+
while (j > 0) {
12+
// Insert nums j into its rightful position in the sorted array
13+
if (nums[j] < nums[j - 1]) {
14+
// Swap them
15+
swap(nums, j, j - 1);
16+
}
17+
j--;
18+
}
19+
20+
}
21+
22+
return nums;
23+
}
24+
public void swap(int[] array, int i, int j) {
25+
int temp = array[i];
26+
array[i] = array[j];
27+
array[j] = temp;
28+
}
29+
}

0 commit comments

Comments
 (0)