Sort an almost sorted array where only two elements where swapped
Given an array where only two elements where swapped , sort the array with O(n) time complexity and one swap
Concept behind:
If you swap two elements in a sorted(ascending) array, the first out of order element will be greater than its next element and the next out of order element will be less than its previous element.
Consider: {10, 20, 40, 30, 50, 60}
Here the first out of order element is 40( 40 > 30) -> a[i] > a[i+1]
The next out of order element is 30 (30 < 40) -> a[i] < a[i-1]
Hence we will first find the first out of order element and from the next element we check for the other out of order element using the above conditions.
Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[] a = {10, 20, 40, 30, 50, 60} ;
int n = a.length;
int index1 = 0;
int index2 = n-1;
for(int i=0; i<n-1; i++){
if(a[i]>a[i+1]) {
index1 = i;
for(int j=i+1; j<n; j++){
if(a[j]<a[j-1]) {
index2 = j;
break;
}
}
break;
}
}
int temp = a[index1];
a[index1] = a[index2];
a[index2] = temp;
for(int i=0; i<n; i++){
System.out.print(a[i]+" ");
}
}
}
Output:
Input: arr[] = {10, 20, 60, 40, 50, 30}
// 30 and 60 are swapped
Output: arr[] = {10, 20, 30, 40, 50, 60}
Input: arr[] = {10, 20, 40, 30, 50, 60}
// 30 and 40 are swapped
Output: arr[] = {10, 20, 30, 40, 50, 60}
Input: arr[] = {1, 5, 3}
// 3 and 5 are swapped
Output: arr[] = {1, 3, 5}
Concept behind:
If you swap two elements in a sorted(ascending) array, the first out of order element will be greater than its next element and the next out of order element will be less than its previous element.
Consider: {10, 20, 40, 30, 50, 60}
Here the first out of order element is 40( 40 > 30) -> a[i] > a[i+1]
The next out of order element is 30 (30 < 40) -> a[i] < a[i-1]
Hence we will first find the first out of order element and from the next element we check for the other out of order element using the above conditions.
Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[] a = {10, 20, 40, 30, 50, 60} ;
int n = a.length;
int index1 = 0;
int index2 = n-1;
for(int i=0; i<n-1; i++){
if(a[i]>a[i+1]) {
index1 = i;
for(int j=i+1; j<n; j++){
if(a[j]<a[j-1]) {
index2 = j;
break;
}
}
break;
}
}
int temp = a[index1];
a[index1] = a[index2];
a[index2] = temp;
for(int i=0; i<n; i++){
System.out.print(a[i]+" ");
}
}
}
Output:
10 20 30 40 50 60
Comments
Post a Comment