Given an array of integers called nums, sort the array in non-decreasing order using the insertion sort algorithm and return the sorted array.
A sorted array in non-decreasing order is an array where each element is greater than or equal to all preceding elements in the array.
Input: nums = [7, 4, 1, 5, 3]
Output: [1, 3, 4, 5, 7]
Explanation: 1 <= 3 <= 4 <= 5 <= 7.
Thus the array is sorted in non-decreasing order.
Input: nums = [5, 4, 4, 1, 1]
Output: [1, 1, 4, 4, 5]
Explanation: 1 <= 1 <= 4 <= 4 <= 5.
Thus the array is sorted in non-decreasing order.
Input: nums = [3, 2, 3, 4, 5]
Insertion sort builds a sorted array one element at a time by repeatedly picking the next element and inserting it into its correct position within the already sorted part of the array.
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
// Insertion Sort
vector<int> insertionSort(vector<int>& nums) {
int n = nums.size();
// Traverse through the array
for (int i = 0; i <= n - 1; i++) {
int j = i;
// Swap elements till we reach a greater element
while (j > 0 && nums[j - 1] > nums[j]) {
swap(nums[j - 1], nums[j]);
j--;
}
}
return nums;
}
};
int main() {
// Create an instance of solution class
Solution solution;
vector<int> nums = {13, 46, 24, 52, 20, 9};
cout << "Before Using Insertion Sort: " << endl;
for (int num : nums) {
cout << num << " ";
}
cout << endl;
// Function call for insertion sort
nums = solution.insertionSort(nums);
cout << "After Using Insertion Sort: " << endl;
for (int num : nums) {
cout << num << " ";
}
cout << endl;
return 0;
}
import java.util.*;
class Solution {
// Insertion Sort
public int[] insertionSort(int[] nums) {
int n = nums.length;
// Traverse through the array
for (int i = 1; i < n; i++) {
int key = nums[i];
int j = i - 1;
// Swap elements till we reach greater element
while (j >= 0 && nums[j] > key) {
nums[j + 1] = nums[j];
j = j - 1;
}
nums[j + 1] = key;
}
return nums;
}
public static void main(String[] args) {
// Create an instance of solution class
Solution solution = new Solution();
int[] nums = {13, 46, 24, 52, 20, 9};
System.out.println("Before Using Insertion Sort: " + Arrays.toString(nums));
// Function call for insertion sort
nums = solution.insertionSort(nums);
System.out.println("After Using Insertion Sort: " + Arrays.toString(nums));
}
}
class Solution:
# Insertion Sort
def insertionSort(self, nums):
n = len(nums)
# Traverse through the array
for i in range(n):
j = i
# Swap elements till we reach greater element
while j > 0 and nums[j - 1] > nums[j]:
nums[j], nums[j - 1] = nums[j - 1], nums[j]
j -= 1
return nums
# Main Function
if __name__ == "__main__":
# Create an instance
solution = Solution()
nums = [13, 46, 24, 52, 20, 9]
print("Before Using Insertion Sort:", nums)
# Call the insertion_sort function
sorted_nums = solution.insertion_sort(nums)
print("After Using Insertion Sort:", sorted_nums)
class Solution {
// Insertion Sort
insertionSort(nums) {
let n = nums.length;
// Traverse through the array
for (let i = 0; i < n; i++) {
let j = i;
// Swap elements till we reach greater element
while (j > 0 && nums[j - 1] > nums[j]) {
[nums[j - 1], nums[j]] = [nums[j], nums[j - 1]];
j--;
}
}
return nums;
}
}
// Create an instance of solution class
let solution = new Solution();
let nums = [13, 46, 24, 52, 20, 9];
console.log("Before Using Insertion Sort:", nums);
// Function call for insertion sort
nums = solution.insertionSort(nums);
console.log("After Using Insertion Sort:", nums);
Q: What happens when the array is reversed?
A: In the worst case (reverse order), each element needs to be compared with all previous elements and shifted to the beginning of the array, leading to O(n2) time complexity.
Q: When is insertion sort efficient?
A: Insertion sort is efficient for small or nearly sorted datasets because fewer shifts are needed, and it avoids unnecessary comparisons. Example: Input: [1, 2, 3, 4, 5] (Sorted) The algorithm completes in O(n) as no shifting is required.
Q: How can insertion sort be optimized?
A: Use binary search to find the correct position for the key in the sorted portion. While this reduces comparisons to O(logn), the shifting operation still takes O(n), so the overall complexity remains O(n2).
Q: Is insertion sort practical for real-world applications?
A: Insertion sort is rarely used for large datasets but is practical for Online Sorting, It is effective for dynamic datasets where elements are added incrementally, as it can quickly re-sort the array. Example: Sorting a deck of cards, where new cards are added one at a time.