Skip to content
This repository has been archived by the owner on Oct 5, 2022. It is now read-only.

Commit

Permalink
Merge pull request #20 from lognoroy/patch-5
Browse files Browse the repository at this point in the history
Create insertion sort.java
  • Loading branch information
SrajanAgrawal committed Oct 3, 2022
2 parents f3e0080 + 0120710 commit 55d9803
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions Java/insertion sort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class Solution {
public int[] sortArray(int[] nums) {
// Insertion Sort in Java
int n = nums.length;

for(int i = 1; i < n; i++) {
int key = nums[i];
int j = (i - 1);
while((j >= 0) && (nums[j] > key)) {
nums[j+1] = nums[j];
j = j - 1;
}
nums[j+1] = key;

}
return nums;
}
}

/* Time Complexity
1. Worst Case = O(n^2) // As all the elements might need to be left shifted n times in a reversed array
2. Average Case = O(n^2)
Space Complexity
1. Worst Case = O(1) // Inplace algorithm
2. Average Case = O(1)
*/

0 comments on commit 55d9803

Please sign in to comment.