Check whether a given array is a k sorted array or not | Java implementation to check whether the given array is a k sorted array or not ; function to check whether the given array is a ' k ' sorted array or not ; auxiliary array ' aux ' ; copy elements of ' arr ' to ' aux ' ; sort ' aux ' ; for every element of ' arr ' at index ' i ' , find its index ' j ' in ' aux ' ; index of arr [ i ] in sorted array ' aux ' ; if abs ( i - j ) > k , then that element is not at - most k distance away from its target position . Thus , ' arr ' is not a k sorted array ; ' arr ' is a k sorted array ; Driver method
import java . util . Arrays ; class Test { static String isKSortedArray ( int arr [ ] , int n , int k ) { int aux [ ] = new int [ n ] ; for ( int i = 0 ; i < n ; i ++ ) aux [ i ] = arr [ i ] ; Arrays . sort ( aux ) ; for ( int i = 0 ; i < n ; i ++ ) { int j = Arrays . binarySearch ( aux , arr [ i ] ) ; if ( Math . abs ( i - j ) > k ) return " No " ; } return " Yes " ; } public static void main ( String args [ ] ) { int arr [ ] = { 3 , 2 , 1 , 5 , 6 , 4 } ; int k = 2 ; System . out . println ( " Is ▁ it ▁ a ▁ k ▁ sorted ▁ array ▁ ? : ▁ " + isKSortedArray ( arr , arr . length , k ) ) ; } }