Problem Statement:
Given a sorted array (ascending) of integers with at most one misplaced element, the task is to output a fixed (completely sorted) array.
Example:
- Input:
[1, 3, 5]- Output:
[1, 3, 5](no changes, already sorted)
- Output:
- Input:
[2, 6, 3, 4, 7, 9]- Output:
[2, 3, 4, 6, 7, 9](move 6 to the correct place)
- Output:
- Input:
[2, 1, 3, 4, 7, 9]- Output:
[1, 2, 3, 4, 7, 9]
- Output:
Solution:
public static int[] sortArray(int[] nums) {
int misplacedIndex = -1;
for(int i = 0; i < nums.length - 1; i++) {
if (nums[i] > nums[i + 1]) {
misplacedIndex = i;
break;
}
}
if (misplacedIndex == -1) return nums;
int[] result = new int[nums.length];
int i = 0, j = misplacedIndex + 1, k = 0;
while(i <= misplacedIndex && j < nums.length) {
if (nums[i] < nums[j]) {
result[k++] = nums[i++];
} else {
result[k++] = nums[j++];
}
}
while(i <= misplacedIndex) {
result[k++] = nums[i++];
}
while(j < nums.length) {
result[k++] = nums[j++];
}
return result;
}Possible Enhancements:
- The given solution has a time complexity of O(n), which is efficient. However, if the array is very large or performance is a concern, consider optimizing further.
- The algorithm iterates through the array twice. This can be reduced to a single pass by performing the sorting in-place, potentially saving memory overhead.
- You can explore alternative sorting algorithms like quicksort or mergesort, which may offer better performance characteristics in certain scenarios. However, for small arrays or nearly sorted arrays, the current solution may already be optimal.
Comments (4)


