Skip to content

Commit 391992d

Browse files
author
Prashant Jain
committed
Added sorting problems
1 parent aa8fe3d commit 391992d

3 files changed

Lines changed: 67 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package in.knowledgegate.dsa.sorting.algos;
2+
3+
/**
4+
* Implement a sorting algo for Insertion Sort
5+
*/
6+
public class InsertionSort implements SortingAlgo {
7+
@Override
8+
public void sort(int[] nums) {
9+
for (int i = 1; i < nums.length; i++) {
10+
int key = nums[i];
11+
int j = i - 1;
12+
while (j >= 0 && nums[j] > key) {
13+
nums[j+1] = nums[j];
14+
j--;
15+
}
16+
nums[j+1] = key;
17+
}
18+
}
19+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package in.knowledgegate.dsa.sorting.algos;
2+
3+
public interface SortingAlgo {
4+
void sort(int[] nums);
5+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package in.knowledgegate.dsa.sorting.problems;
2+
3+
/**
4+
* Given an integer array nums sorted in
5+
* non-decreasing order, return an array of the
6+
* squares of each number sorted in non-decreasing
7+
* order.
8+
*
9+
* Example 1:
10+
* Input: nums = [-4,-1,0,3,10]
11+
* Output: [0,1,9,16,100]
12+
* Explanation: After squaring, the array becomes
13+
* [16,1,0,9,100].
14+
* After sorting, it becomes [0,1,9,16,100].
15+
*
16+
* Example 2:
17+
* Input: nums = [-7,-3,2,3,11]
18+
* Output: [4,9,9,49,121]
19+
*
20+
*
21+
* Constraints:
22+
* 1 <= nums.length <= 104
23+
* -104 <= nums[i] <= 104
24+
* nums is sorted in non-decreasing order.
25+
*/
26+
public class SquaresOfSortedArray {
27+
public int[] sortedSquares(int[] nums) {
28+
int beg = 0, end = nums.length - 1;
29+
int[] result = new int[nums.length];
30+
for (int i = 0; i < nums.length; i++) {
31+
int sq1 = (int) Math.pow(nums[beg], 2);
32+
int sq2 = (int) Math.pow(nums[end], 2);
33+
if (sq1 >= sq2) {
34+
result[nums.length - 1 - i] = sq1;
35+
beg++;
36+
} else {
37+
result[nums.length - 1 - i] = sq2;
38+
end--;
39+
}
40+
}
41+
return result;
42+
}
43+
}

0 commit comments

Comments
 (0)