"Smallest substring occurring only once in a given string | Java program for the above approach ; Function to find the smallest substring occurring only once ; Stores all occurences ; Generate all the substrings ; Avoid multiple occurences ; Append all substrings ; Take into account all the substrings ; Iterate over all unique substrings ; If frequency is 1 ; Append into fresh list ; Initialize a dictionary ; Append the keys ; Traverse the dictionary ; Return the minimum of dictionary ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static int smallestSubstring ( String a ) { ArrayList < String > a1 = new ArrayList < > ( ) ; for ( int i = 0 ; i < a . length ( ) ; i ++ ) { for ( int j = i + 1 ; j <= a . length ( ) ; j ++ ) { if ( i != j ) a1 . add ( a . substring ( i , j ) ) ; } } TreeMap < String , Integer > a2 = new TreeMap < > ( ) ; for ( String s : a1 ) a2 . put ( s , a2 . getOrDefault ( s , 0 ) + 1 ) ; ArrayList < String > freshlist = new ArrayList < > ( ) ; for ( String s : a2 . keySet ( ) ) { if ( a2 . get ( s ) == 1 ) freshlist . add ( s ) ; } TreeMap < String , Integer > dictionary = new TreeMap < > ( ) ; for ( String s : freshlist ) { dictionary . put ( s , s . length ( ) ) ; } ArrayList < Integer > newlist = new ArrayList < > ( ) ; for ( String s : dictionary . keySet ( ) ) newlist . add ( dictionary . get ( s ) ) ; int ans = Integer . MAX_VALUE ; for ( int i : newlist ) ans = Math . min ( ans , i ) ; return ans == Integer . MAX_VALUE ? 0 : ans ; } public static void main ( String [ ] args ) { String S = " ababaabba " ; System . out . println ( smallestSubstring ( S ) ) ; } }


"Smallest substring with each letter occurring both in uppercase and lowercase | Java program for the above approach ; Function to check if the current string is balanced or not ; For every character , check if there exists uppercase as well as lowercase characters ; Function to find smallest length substring in the given string which is balanced ; Store frequency of lowercase characters ; Stores frequency of uppercase characters ; Count frequency of characters ; Mark those characters which are not present in both lowercase and uppercase ; Initialize the frequencies back to 0 ; Marks the start and end of current substring ; Marks the start and end of required substring ; Stores the length of smallest balanced substring ; Remove all characters obtained so far ; Remove extra characters from front of the current substring ; If substring ( st , i ) is balanced ; No balanced substring ; Store answer string ; Driver Code ; Given string"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static boolean balanced ( int small [ ] , int caps [ ] ) { for ( int i = 0 ; i < 26 ; i ++ ) { if ( small [ i ] != 0 && ( caps [ i ] == 0 ) ) return false ; else if ( ( small [ i ] == 0 ) && ( caps [ i ] != 0 ) ) return false ; } return true ; } static void smallestBalancedSubstring ( String s ) { int [ ] small = new int [ 26 ] ; int [ ] caps = new int [ 26 ] ; Arrays . fill ( small , 0 ) ; Arrays . fill ( caps , 0 ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) >= 65 && s . charAt ( i ) <= 90 ) caps [ s . charAt ( i ) - ' A ' ] ++ ; else small [ s . charAt ( i ) - ' a ' ] ++ ; } Map < Character , Integer > mp = new HashMap < Character , Integer > ( ) ; for ( int i = 0 ; i < 26 ; i ++ ) { if ( small [ i ] != 0 && caps [ i ] == 0 ) mp . put ( ( char ) ( i + ' a ' ) , 1 ) ; else if ( caps [ i ] != 0 && small [ i ] == 0 ) mp . put ( ( char ) ( i + ' A ' ) , 1 ) ; } Arrays . fill ( small , 0 ) ; Arrays . fill ( caps , 0 ) ; int i = 0 , st = 0 ; int start = - 1 , end = - 1 ; int minm = Integer . MAX_VALUE ; while ( i < s . length ( ) ) { if ( mp . get ( s . charAt ( i ) ) != null ) { while ( st < i ) { if ( s . charAt ( st ) >= 65 && s . charAt ( st ) <= 90 ) caps [ s . charAt ( st ) - ' A ' ] -- ; else small [ s . charAt ( st ) - ' a ' ] -- ; st ++ ; } i += 1 ; st = i ; } else { if ( s . charAt ( i ) >= 65 && s . charAt ( i ) <= 90 ) caps [ s . charAt ( i ) - ' A ' ] ++ ; else small [ s . charAt ( i ) - ' a ' ] ++ ; while ( true ) { if ( s . charAt ( st ) >= 65 && s . charAt ( st ) <= 90 && caps [ s . charAt ( st ) - ' A ' ] > 1 ) { caps [ s . charAt ( st ) - ' A ' ] -- ; st ++ ; } else if ( s . charAt ( st ) >= 97 && s . charAt ( st ) <= 122 && small [ s . charAt ( st ) - ' a ' ] > 1 ) { small [ s . charAt ( st ) - ' a ' ] -- ; st ++ ; } else break ; } if ( balanced ( small , caps ) ) { if ( minm > ( i - st + 1 ) ) { minm = i - st + 1 ; start = st ; end = i ; } } i += 1 ; } } if ( start == - 1 end == - 1 ) System . out ....


"Smallest sum contiguous subarray | Java implementation to find the smallest sum contiguous subarray ; function to find the smallest sum contiguous subarray ; to store the minimum value that is ending up to the current index ; to store the minimum value encountered so far ; traverse the array elements ; if min_ending_here > 0 , then it could not possibly contribute to the minimum sum further ; else add the value arr [ i ] to min_ending_here ; update min_so_far ; required smallest sum contiguous subarray value ; Driver method"
How can the above be solved in Java?

class GFG { static int smallestSumSubarr ( int arr [ ] , int n ) { int min_ending_here = 2147483647 ; int min_so_far = 2147483647 ; for ( int i = 0 ; i < n ; i ++ ) { if ( min_ending_here > 0 ) min_ending_here = arr [ i ] ; else min_ending_here += arr [ i ] ; min_so_far = Math . min ( min_so_far , min_ending_here ) ; } return min_so_far ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , - 4 , 2 , - 3 , - 1 , 7 , - 5 } ; int n = arr . length ; System . out . print ( " Smallest ▁ sum : ▁ " + smallestSumSubarr ( arr , n ) ) ; } }


"Smallest sum contiguous subarray | Set | Java program for Smallest sum contiguous subarray | Set 2 ; function to find the smallest sum contiguous subarray ; First invert the sign of the elements ; Apply the normal Kadane algorithm But on the elements Of the array having inverted sign ; Invert the answer to get minimum val ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static int smallestSumSubarr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = - arr [ i ] ; int sum_here = arr [ 0 ] , max_sum = arr [ 0 ] ; for ( int i = 1 ; i < n ; i ++ ) { sum_here = Math . max ( sum_here + arr [ i ] , arr [ i ] ) ; max_sum = Math . max ( max_sum , sum_here ) ; } return ( - 1 ) * max_sum ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , - 4 , 2 , - 3 , - 1 , 7 , - 5 } ; int n = arr . length ; System . out . print ( " Smallest ▁ sum : ▁ " + smallestSumSubarr ( arr , n ) ) ; } }


"Smallest triangular number larger than p | Java code to find the bucket to choose for picking flowers out of it ; Driver code"
How can the above be solved in Java?

import java . lang . System . * ; class GFG { static int findBucketNo ( int p ) { return ( int ) Math . ceil ( ( Math . sqrt ( 8 * p + 1 ) - 1 ) / 2 ) ; } public static void main ( String [ ] args ) { int p = 10 ; System . out . println ( findBucketNo ( p ) ) ; } }


"Smallest value in each level of Binary Tree | JAVA program to print minimum element in each level of binary tree . ; A Binary Tree Node ; return height of tree ; Iterative method to find every level minimum element of Binary Tree ; Base Case ; Create an empty queue for level order traversal ; push the root for Change the level ; for go level by level ; for check the level ; Get top of queue ; if node == null ( Means this is boundary between two levels ) ; here queue is empty represent no element in the actual queue ; increment level ; Reset min for next level minimum value ; get Minimum in every level ; Enqueue left child ; Enqueue right child ; Utility function to create a new tree node ; Driver code ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1"
How can the above be solved in Java?

 import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } ; static int heightoftree ( Node root ) { if ( root == null ) return 0 ; int left = heightoftree ( root . left ) ; int right = heightoftree ( root . right ) ; return ( ( left > right ? left : right ) + 1 ) ; } static void printPerLevelMinimum ( Node root ) { if ( root == null ) return ; Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root ) ; q . add ( null ) ; int min = Integer . MAX_VALUE ; int level = 0 ; while ( q . isEmpty ( ) == false ) { Node node = q . peek ( ) ; q . remove ( ) ; if ( node == null ) { System . out . print ( " level ▁ " + level + " ▁ min ▁ is ▁ = ▁ " + min + "
"); if ( q . isEmpty ( ) ) break ; q . add ( null ) ; level ++ ; min = Integer . MAX_VALUE ; continue ; } if ( min > node . data ) min = node . data ; if ( node . left != null ) { q . add ( node . left ) ; } if ( node . right != null ) { q . add ( node . right ) ; } } } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } public static void main ( String [ ] args ) { Node root = newNode ( 7 ) ; root . left = newNode ( 6 ) ; root . right = newNode ( 5 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 3 ) ; root . right . left = newNode ( 2 ) ; root . right . right = newNode ( 1 ) ; System . out . print ( " Every ▁ Level ▁ minimum ▁ is " + "
"); printPerLevelMinimum ( root ) ; } }


"Smallest value in each level of Binary Tree | Java program to print smallest element in each level of binary tree . ; A Binary Tree Node ; return height of tree ; Inorder Traversal Search minimum element in each level and store it into vector array . ; height of tree for the size of vector array ; vector for store all minimum of every level ; save every level minimum using inorder traversal ; print every level minimum ; Utility function to create a new tree node ; Driver Code ; Let us create binary tree shown in above diagram ; 7 / \ 6 5 / \ / \ 4 3 2 1"
How can the above be solved in Java?

 import java . util . Arrays ; class GFG { static int INT_MAX = ( int ) 10e6 ; static class Node { int data ; Node left , right ; } ; static int heightoftree ( Node root ) { if ( root == null ) return 0 ; int left = heightoftree ( root . left ) ; int right = heightoftree ( root . right ) ; return ( ( left > right ? left : right ) + 1 ) ; } static void printPerLevelMinimum ( Node root , int [ ] res , int level ) { if ( root != null ) { printPerLevelMinimum ( root . left , res , level + 1 ) ; if ( root . data < res [ level ] ) res [ level ] = root . data ; printPerLevelMinimum ( root . right , res , level + 1 ) ; } } static void perLevelMinimumUtility ( Node root ) { int n = heightoftree ( root ) , i ; int [ ] res = new int [ n ] ; Arrays . fill ( res , INT_MAX ) ; printPerLevelMinimum ( root , res , 0 ) ; System . out . print ( "Every level minimum is
"); for ( i = 0 ; i < n ; i ++ ) { System . out . print ( " level ▁ " + i + " ▁ min ▁ is ▁ = ▁ " + res [ i ] + "
"); } } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } public static void main ( String [ ] args ) { Node root = newNode ( 7 ) ; root . left = newNode ( 6 ) ; root . right = newNode ( 5 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 3 ) ; root . right . left = newNode ( 2 ) ; root . right . right = newNode ( 1 ) ; perLevelMinimumUtility ( root ) ; } }


"Smallest value of N such that the sum of all natural numbers from K to N is at least X | Java program for the above approach ; Function to check if the sum of natural numbers from K to N is >= X ; Function to find the minimum value of N such that the sum of natural numbers from K to N is at least X ; If K is greater than X ; Perform the Binary Search ; If the sum of the natural numbers from K to mid is atleast X ; Update res ; Update high ; Otherwise , update low ; Print the value of res as the answer ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static boolean isGreaterEqual ( int N , int K , int X ) { return ( ( N * 1L * ( N + 1 ) / 2 ) - ( ( K - 1 ) * 1L * K / 2 ) ) >= X ; } static void minimumNumber ( int K , int X ) { if ( K > X ) { System . out . println ( " - 1" ) ; return ; } int low = K , high = X , res = - 1 ; while ( low <= high ) { int mid = low + ( high - low ) / 2 ; if ( isGreaterEqual ( mid , K , X ) ) { res = mid ; high = mid - 1 ; } else low = mid + 1 ; } System . out . println ( res ) ; } public static void main ( String [ ] args ) { int K = 5 , X = 13 ; minimumNumber ( K , X ) ; } }


"Smallest value of N such that the sum of all natural numbers from K to N is at least X | Java program for the above approach ; Function to find the minimum possible value of N such that sum of natural numbers from K to N is at least X ; If K is greater than X ; Stores value of minimum N ; Stores the sum of values over the range [ K , ans ] ; Iterate over the range [ K , N ] ; Check if sum of first i natural numbers is >= X ; Print the possible value of ans ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void minimumNumber ( int K , int X ) { if ( K > X ) { System . out . println ( " - 1" ) ; return ; } int ans = 0 ; int sum = 0 ; for ( int i = K ; i <= X ; i ++ ) { sum += i ; if ( sum >= X ) { ans = i ; break ; } } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int K = 5 , X = 13 ; minimumNumber ( K , X ) ; } }


"Smallest value of X satisfying the condition X % A [ i ] = B [ i ] for two given arrays | Java program for the above approach ; Function to calculate modulo inverse of a w . r . t m using Extended Euclid Algorithm ; Base Case ; Perform extended euclid algorithm ; q is quotient ; m is remainder now , process same as euclid 's algorithm ; If x1 is negative ; Make x1 positive ; Function to implement Chinese Remainder Theorem to find X ; Stores the product of array elements ; Traverse the array ; Update product ; Initialize the result ; Apply the above formula ; Function to calculate the product of all elements of the array a [ ] ; Stores product of all array elements ; Traverse the array ; Return the product ; Function to find the value of X that satisfies the given condition ; Stores the required smallest value using Chinese Remainder Theorem ; Stores the product of all array elements ; The equation is Y + K * M >= P Therefore , calculate K = ceil ( ( P - Y ) / M ) ; So , X = Y + K * M ; Print the resultant value of X ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; public class Main { static int inv ( int a , int m ) { int m0 = m , t , q ; int x0 = 0 , x1 = 1 ; if ( m == 1 ) return 0 ; while ( a > 1 ) { q = a / m ; t = m ; m = a % m ; a = t ; t = x0 ; x0 = x1 - q * x0 ; x1 = t ; } if ( x1 < 0 ) x1 += m0 ; return x1 ; } static int findMinX ( int A [ ] , int B [ ] , int N ) { int prod = 1 ; for ( int i = 0 ; i < N ; i ++ ) prod *= A [ i ] ; int result = 0 ; for ( int i = 0 ; i < N ; i ++ ) { int pp = prod / A [ i ] ; result += B [ i ] * inv ( pp , A [ i ] ) * pp ; } return result % prod ; } static int product ( int a [ ] ) { int ans = 1 ; for ( int i = 0 ; i < a . length ; i ++ ) { ans *= a [ i ] ; } return ans ; } public static void findSmallestInteger ( int A [ ] , int B [ ] , int P ) { int Y = findMinX ( A , B , A . length ) ; int M = product ( A ) ; int K = ( int ) Math . ceil ( ( ( double ) P - ( double ) Y ) / ( double ) M ) ; int X = Y + K * M ; System . out . println ( X ) ; } public static void main ( String [ ] args ) { int A [ ] = { 3 , 4 , 5 } ; int B [ ] = { 2 , 3 , 1 } ; int P = 72 ; findSmallestInteger ( A , B , P ) ; } }


"Smallest window that contains all characters of string itself | Java program to find the smallest window containing all characters of a pattern . ; Function to find smallest window containing all distinct characters ; Count all distinct characters . ; Now follow the algorithm discussed in below ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static String findSubString ( String str ) { int n = str . length ( ) ; int dist_count = 0 ; HashMap < Character , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( mp . containsKey ( str . charAt ( i ) ) ) { Integer a = mp . get ( str . charAt ( i ) ) ; mp . put ( str . charAt ( i ) , a + 1 ) ; } else { mp . put ( str . charAt ( i ) , 1 ) ; } } dist_count = mp . size ( ) ; int size = Integer . MAX_VALUE ; String res = " " ; for ( int i = 0 ; i < n ; i ++ ) { int count = 0 ; int visited [ ] = new int [ 256 ] ; for ( int j = 0 ; j < 256 ; j ++ ) visited [ j ] = 0 ; String sub_str = " " ; for ( int j = i ; j < n ; j ++ ) { if ( visited [ str . charAt ( j ) ] == 0 ) { count ++ ; visited [ str . charAt ( j ) ] = 1 ; } sub_str += str . charAt ( j ) ; if ( count == dist_count ) break ; } if ( sub_str . length ( ) < size && count == dist_count ) { res = sub_str ; size = res . length ( ) ; } } return res ; } public static void main ( String [ ] args ) { String str = " aabcbcdbca " ; System . out . println ( " Smallest ▁ window ▁ containing ▁ all ▁ distinct " + " ▁ characters ▁ is : ▁ " + findSubString ( str ) ) ; } }


"Smallest x such that 1 * n , 2 * n , ... x * n have all digits from 1 to 9 | Java program to find x such that 1 * n , 2 * n , 3 * n ... x * n have all digits from 1 to 9 at least once ; Returns smallest value x such that 1 * n , 2 * n , 3 * n ... x * n have all digits from 1 to 9 at least once ; taking temporary array and variable . ; iterate till we get all the 10 digits at least once ; checking all the digits ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static int smallestX ( int n ) { int [ ] temp = new int [ 10 ] ; for ( int i = 0 ; i < 10 ; i ++ ) temp [ i ] = 0 ; if ( n == 0 ) return - 1 ; int count = 0 , x = 0 ; for ( x = 1 ; count < 10 ; x ++ ) { int y = x * n ; while ( y > 0 ) { if ( temp [ y % 10 ] == 0 ) { count ++ ; temp [ y % 10 ] = 1 ; } y /= 10 ; } } return x - 1 ; } public static void main ( String args [ ] ) { int n = 5 ; System . out . print ( smallestX ( n ) ) ; } }


"Smarandache | Java program to print the first ' n ' terms of the Smarandache - Wellin Sequence ; Function to collect first ' n ' prime numbers ; List to store first ' n ' primes ; Function to generate Smarandache - Wellin Sequence ; Storing the first ' n ' prime numbers in a list ; Driver Code"
How can the above be solved in Java?

class GFG { static void primes ( int n ) { int i = 2 ; int j = 0 ; int [ ] result = new int [ n ] ; int z = 0 ; while ( j < n ) { boolean flag = true ; for ( int item = 2 ; item <= ( int ) ( i * 1 / 2 ) ; item ++ ) if ( i % item == 0 && i != item ) { flag = false ; break ; } if ( flag ) { result [ z ++ ] = i ; j += 1 ; } i += 1 ; } for ( i = 0 ; i < result . length ; i ++ ) { for ( j = 0 ; j <= i ; j ++ ) System . out . print ( result [ j ] ) ; System . out . print ( " ▁ " ) ; } } static void smar_wln ( int n ) { primes ( n ) ; } public static void main ( String [ ] args ) { int n = 5 ; System . out . println ( " First ▁ " + n + " ▁ terms ▁ of ▁ the ▁ Sequence ▁ are " ) ; smar_wln ( n ) ; } }


"Smith Number | Java program to to check whether a number is Smith Number or not . ; array to store all prime less than and equal to 10 ^ 6 ; utility function for sieve of sundaram ; In general Sieve of Sundaram , produces primes smaller than ( 2 * x + 2 ) for a number given number x . Since we want primes smaller than MAX , we reduce MAX to half This array is used to separate numbers of the form i + j + 2 ij from others where 1 <= i <= j ; Main logic of Sundaram . Mark all numbers which do not generate prime number by doing 2 * i + 1 ; Since 2 is a prime number ; Print other primes . Remaining primes are of the form 2 * i + 1 such that marked [ i ] is false . ; Returns true if n is a Smith number , else false . ; Find sum the digits of prime factors of n ; If primes [ i ] is a prime factor , add its digits to pDigitSum . ; If n != 1 then one prime factor still to be summed up ; ; All prime factors digits summed up Now sum the original number digits ; If sum of digits in prime factors and sum of digits in original number are same , then return true . Else return false . ; Driver method ; Finding all prime numbers before limit . These numbers are used to find prime factors ."
How can the above be solved in Java?

import java . util . Vector ; class Test { static int MAX = 10000 ; static Vector < Integer > primes = new Vector < > ( ) ; static void sieveSundaram ( ) { boolean marked [ ] = new boolean [ MAX / 2 + 100 ] ; for ( int i = 1 ; i <= ( Math . sqrt ( MAX ) - 1 ) / 2 ; i ++ ) for ( int j = ( i * ( i + 1 ) ) << 1 ; j <= MAX / 2 ; j = j + 2 * i + 1 ) marked [ j ] = true ; primes . addElement ( 2 ) ; for ( int i = 1 ; i <= MAX / 2 ; i ++ ) if ( marked [ i ] == false ) primes . addElement ( 2 * i + 1 ) ; } static boolean isSmith ( int n ) { int original_no = n ; int pDigitSum = 0 ; for ( int i = 0 ; primes . get ( i ) <= n / 2 ; i ++ ) { while ( n % primes . get ( i ) == 0 ) { int p = primes . get ( i ) ; n = n / p ; while ( p > 0 ) { pDigitSum += ( p % 10 ) ; p = p / 10 ; } } } if ( n != 1 && n != original_no ) { while ( n > 0 ) { pDigitSum = pDigitSum + n % 10 ; n = n / 10 ; } } int sumDigits = 0 ; while ( original_no > 0 ) { sumDigits = sumDigits + original_no % 10 ; original_no = original_no / 10 ; } return ( pDigitSum == sumDigits ) ; } public static void main ( String [ ] args ) { sieveSundaram ( ) ; System . out . println ( " Printing ▁ first ▁ few ▁ Smith ▁ Numbers " + " ▁ using ▁ isSmith ( ) " ) ; for ( int i = 1 ; i < 500 ; i ++ ) if ( isSmith ( i ) ) System . out . print ( i + " ▁ " ) ; } }


"Snake case of a given sentence | Java program to convert given sentence to snake case ; Function to replace spaces and convert into snake case ; Converting space to underscor ; If not space , convert into lower character ; Driver Code ; Calling function"
How can the above be solved in Java?

import java . io . * ; class GFG { static void convert ( String str ) { int n = str . length ( ) ; String str1 = " " ; for ( int i = 0 ; i < n ; i ++ ) { if ( str . charAt ( i ) == ' ▁ ' ) str1 = str1 + ' _ ' ; else str1 = str1 + Character . toLowerCase ( str . charAt ( i ) ) ; } System . out . print ( str1 ) ; } public static void main ( String args [ ] ) { String str = " I ▁ got ▁ intern ▁ at ▁ geeksforgeeks " ; convert ( str ) ; } }


"Solve Linear Congruences Ax = B ( mod N ) for values of x in range [ 0 , N | Java program for the above approach ; Function to stores the values of x and y and find the value of gcd ( a , b ) ; Base Case ; Store the result of recursive call ; Update x and y using results of recursive call ; Function to give the distinct solutions of ax = b ( mod n ) ; Function Call to find the value of d and u ; No solution exists ; Else , initialize the value of x0 ; Print all the answers ; Driver Code ; Input ; Function Call"
How can the above be solved in Java?

import java . io . * ; class GFG { public static long [ ] ExtendedEuclidAlgo ( long a , long b ) { if ( a == 0 ) { return new long [ ] { b , 0 , 1 } ; } else { long x1 = 1 , y1 = 1 ; long gcdy [ ] = ExtendedEuclidAlgo ( b % a , a ) ; long gcd = gcdy [ 0 ] ; x1 = gcdy [ 1 ] ; y1 = gcdy [ 2 ] ; long y = x1 ; long x = y1 - ( long ) Math . floor ( b / a ) * x1 ; return new long [ ] { gcd , x , y } ; } } public static void linearCongruence ( long A , long B , long N ) { A = A % N ; B = B % N ; long u = 0 , v = 0 ; long person [ ] = ExtendedEuclidAlgo ( A , N ) ; long d = person [ 0 ] ; u = person [ 1 ] ; v = person [ 2 ] ; if ( B % d != 0 ) { System . out . println ( - 1 ) ; return ; } long x0 = ( u * ( B / d ) ) % N ; if ( x0 < 0 ) x0 += N ; for ( long i = 0 ; i <= d - 1 ; i ++ ) { long an = ( x0 + i * ( N / d ) ) % N ; System . out . print ( an + " ▁ " ) ; } } public static void main ( String [ ] args ) { long A = 15 ; long B = 9 ; long N = 18 ; linearCongruence ( A , B , N ) ; } }


"Solve the Linear Equation of Single Variable | Java program to solve the given equation ; Function to solve the given equation ; Traverse the equation ; For cases such as : x , - x , + x ; Flip sign once ' = ' is seen ; There may be a number left in the end ; For infinite solutions ; For no solution ; x = total sum / coeff of x ' - ' sign indicates moving numeric value to right hand side ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static String solveEquation ( String equation ) { int n = equation . length ( ) , sign = 1 , coeff = 0 ; int total = 0 , i = 0 ; for ( int j = 0 ; j < n ; j ++ ) { if ( equation . charAt ( j ) == ' + ' || equation . charAt ( j ) == ' - ' ) { if ( j > i ) total += sign * Integer . parseInt ( equation . substring ( i , j ) ) ; i = j ; } else if ( equation . charAt ( j ) == ' x ' ) { if ( ( i == j ) || equation . charAt ( j - 1 ) == ' + ' ) coeff += sign ; else if ( equation . charAt ( j - 1 ) == ' - ' ) coeff -= sign ; else coeff += sign * Integer . parseInt ( equation . substring ( i , j ) ) ; i = j + 1 ; } else if ( equation . charAt ( j ) == ' = ' ) { if ( j > i ) total += sign * Integer . parseInt ( equation . substring ( i , j ) ) ; sign = - 1 ; i = j + 1 ; } } if ( i < n ) total = total + sign * Integer . parseInt ( equation . substring ( i ) ) ; if ( coeff == 0 && total == 0 ) return " Infinite ▁ solutions " ; if ( coeff == 0 && total != 0 ) return " No ▁ solution " ; int ans = - total / coeff ; return ( Integer . toString ( ans ) ) ; } public static void main ( String args [ ] ) { String equation = new String ( " x + 5-3 + x = 6 + x - 2" ) ; System . out . print ( " x ▁ = ▁ " + solveEquation ( equation ) ) ; } }


"Solve the Logical Expression given by string | Java program to solve the logical expression . ; Function to evaluate the logical expression ; traversing string from the end . ; for NOT operation ; for AND and OR operation ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static char logicalExpressionEvaluation ( String str ) { Stack < Character > arr = new Stack < Character > ( ) ; for ( int i = str . length ( ) - 1 ; i >= 0 ; i -- ) { if ( str . charAt ( i ) == ' [ ' ) { Vector < Character > s = new Stack < Character > ( ) ; while ( arr . peek ( ) != ' ] ' ) { s . add ( arr . peek ( ) ) ; arr . pop ( ) ; } arr . pop ( ) ; if ( s . size ( ) == 3 ) { arr . push ( s . get ( 2 ) == '1' ? '0' : '1' ) ; } else if ( s . size ( ) == 5 ) { int a = s . get ( 0 ) - 48 , b = s . get ( 4 ) - 48 , c ; if ( s . get ( 2 ) == ' & ' ) { c = a & b ; } else { c = a | b ; } arr . push ( ( char ) ( c + 48 ) ) ; } } else { arr . push ( str . charAt ( i ) ) ; } } return arr . peek ( ) ; } public static void main ( String [ ] args ) { String str = " [ | , [ & ,1 , [ ! , 0 ] ] , [ ! , [ | , [ ▁ , 1,0 ] , [ ! ,1 ] ] ] ] " ; System . out . println ( logicalExpressionEvaluation ( str ) ) ; } }


"Solving f ( n ) = ( 1 ) + ( 2 * 3 ) + ( 4 * 5 * 6 ) . . . n using Recursion | Java Program to print the solution of the series f ( n ) = ( 1 ) + ( 2 * 3 ) + ( 4 * 5 * 6 ) . . . n using recursion ; * * Recursive method for finding * sum of series * * @ param calculated number of terms * till which sum of terms has been * calculated @ param current number of * terms for which sum has to be calculated . * @ param N Number of terms in the function * to be calculated @ return sum ; checking termination condition ; product of terms till current ; recursive call for adding terms next in the series ; Driver Code ; input number of terms in the series ; invoking the method to calculate the sum"
How can the above be solved in Java?

class GFG { static int seriesSum ( int calculated , int current , int N ) { int i , cur = 1 ; if ( current == N + 1 ) return 0 ; for ( i = calculated ; i < calculated + current ; i ++ ) cur *= i ; return cur + seriesSum ( i , current + 1 , N ) ; } public static void main ( String [ ] args ) { int N = 5 ; System . out . println ( seriesSum ( 1 , 1 , N ) ) ; } }


"Sort 1 to N by swapping adjacent elements | Java program to test whether an array can be sorted by swapping adjacent elements using boolean array ; Return true if array can be sorted otherwise false ; Check bool array B and sorts elements for continuous sequence of 1 ; Sort array A from i to j ; Check if array is sorted or not ; Driver program to test sortedAfterSwap ( )"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static boolean sortedAfterSwap ( int A [ ] , boolean B [ ] , int n ) { int i , j ; for ( i = 0 ; i < n - 1 ; i ++ ) { if ( B [ i ] ) { j = i ; while ( B [ j ] ) { j ++ ; } Arrays . sort ( A , i , 1 + j ) ; i = j ; } } for ( i = 0 ; i < n ; i ++ ) { if ( A [ i ] != i + 1 ) { return false ; } } return true ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 2 , 5 , 3 , 4 , 6 } ; boolean B [ ] = { false , true , true , true , false } ; int n = A . length ; if ( sortedAfterSwap ( A , B , n ) ) { System . out . println ( " A ▁ can ▁ be ▁ sorted " ) ; } else { System . out . println ( " A ▁ can ▁ not ▁ be ▁ sorted " ) ; } } }


"Sort 1 to N by swapping adjacent elements | Java program to test whether an array can be sorted by swapping adjacent elements using boolean array ; Return true if array can be sorted otherwise false ; Check if array is sorted or not ; Driver Code"
How can the above be solved in Java?

class GFG { static int sortedAfterSwap ( int [ ] A , int [ ] B , int n ) { int t = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( B [ i ] != 0 ) { if ( A [ i ] != i + 1 ) t = A [ i ] ; A [ i ] = A [ i + 1 ] ; A [ i + 1 ] = t ; } } for ( int i = 0 ; i < n ; i ++ ) { if ( A [ i ] != i + 1 ) return 0 ; } return 1 ; } public static void main ( String [ ] args ) { int [ ] A = { 1 , 2 , 5 , 3 , 4 , 6 } ; int [ ] B = { 0 , 1 , 1 , 1 , 0 } ; int n = A . length ; if ( sortedAfterSwap ( A , B , n ) == 0 ) System . out . println ( " A ▁ can ▁ be ▁ sorted " ) ; else System . out . println ( " A ▁ can ▁ not ▁ be ▁ sorted " ) ; } }


"Sort 3 numbers | Java program to sort an array of size 3 ; Insert arr [ 1 ] ; Insert arr [ 2 ] ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void sort3 ( int arr [ ] , int temp [ ] ) { if ( arr [ 1 ] < arr [ 0 ] ) { temp [ 0 ] = arr [ 0 ] ; arr [ 0 ] = arr [ 1 ] ; arr [ 1 ] = temp [ 0 ] ; } if ( arr [ 2 ] < arr [ 1 ] ) { temp [ 0 ] = arr [ 1 ] ; arr [ 1 ] = arr [ 2 ] ; arr [ 2 ] = temp [ 0 ] ; if ( arr [ 1 ] < arr [ 0 ] ) { temp [ 0 ] = arr [ 0 ] ; arr [ 0 ] = arr [ 1 ] ; arr [ 1 ] = temp [ 0 ] ; } } } public static void main ( String args [ ] ) { int a [ ] = new int [ ] { 10 , 12 , 5 } ; int temp1 [ ] = new int [ 10 ] ; sort3 ( a , temp1 ) ; for ( int i = 0 ; i < 3 ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } }


"Sort 3 numbers | Java program to sort an array of size 3"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { public static void main ( String [ ] args ) { int a [ ] = { 10 , 12 , 5 } ; Arrays . sort ( a ) ; for ( int i = 0 ; i < 3 ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } }


"Sort Array such that smallest is at 0 th index and next smallest it at last index and so on | Java program for the above approach ; Function to perform the rearrangement ; Initialize variables ; Loop until i crosses j ; This check is to find the minimum values in the ascending order ; Condition to alternatively iterate variable i and j ; Perform swap operation ; Increment i ; Assign the value of min ; Perform swap ; Decrement i ; Assign the value of min ; Print the array ; Driver Code ; Given Array arr [ ] ; Function Call"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; public class GFG { static void rearrange ( int [ ] a ) { int i = 0 , j = a . length - 1 ; int min = 0 , k , x = 0 , temp ; while ( i < j ) { for ( k = i ; k <= j ; k ++ ) { if ( a [ k ] < a [ min ] ) min = k ; } if ( x % 2 == 0 ) { temp = a [ i ] ; a [ i ] = a [ min ] ; a [ min ] = temp ; i ++ ; min = i ; } else { temp = a [ j ] ; a [ j ] = a [ min ] ; a [ min ] = temp ; j -- ; min = j ; } x ++ ; } for ( i = 0 ; i < a . length ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 3 , 4 , 5 } ; rearrange ( arr ) ; } }


"Sort M elements of given circular array starting from index K | Java program for the above approach ; Function to print the circular array ; Print the array ; Function to sort m elements of diven circular array starting from index k ; Traverse M elements ; Iterate from index k to k + m - 1 ; Check if the next element in the circular array is less than the current element ; Swap current element with the next element ; Print the circular array ; Driver Code ; Function Call"
How can the above be solved in Java?

class GFG { static void printCircularArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } static void sortCircularArray ( int arr [ ] , int n , int k , int m ) { for ( int i = 0 ; i < m ; i ++ ) { for ( int j = k ; j < k + m - 1 ; j ++ ) { if ( arr [ j % n ] > arr [ ( j + 1 ) % n ] ) { int t = arr [ j % n ] ; arr [ j % n ] = arr [ ( j + 1 ) % n ] ; arr [ ( j + 1 ) % n ] = t ; } } } printCircularArray ( arr , n ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 4 , 1 , 6 , 5 , 3 } ; int K = 2 , M = 3 ; int N = arr . length ; sortCircularArray ( arr , N , K , M ) ; } }


"Sort a binary array using one traversal | JAVA Code for Sort a binary array using one traversal ; if number is smaller than 1 then swap it with j - th number ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; class GFG { static void sortBinaryArray ( int a [ ] , int n ) { int j = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] < 1 ) { j ++ ; int temp = a [ j ] ; a [ j ] = a [ i ] ; a [ i ] = temp ; } } } public static void main ( String [ ] args ) { int a [ ] = { 1 , 0 , 0 , 1 , 0 , 1 , 0 , 1 , 1 , 1 , 1 , 1 , 1 , 0 , 0 , 1 , 1 , 0 , 1 , 0 , 0 } ; int n = a . length ; sortBinaryArray ( a , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } }


"Sort a linked list of 0 s , 1 s and 2 s | Java program to sort a linked list of 0 , 1 and 2 ; head of list ; Linked list Node ; initialise count of 0 1 and 2 as 0 ; count total number of '0' , '1' and '2' * count [ 0 ] will store total number of '0' s * count [ 1 ] will store total number of '1' s * count [ 2 ] will store total number of '2' s ; Let say count [ 0 ] = n1 , count [ 1 ] = n2 and count [ 2 ] = n3 * now start traversing list from head node , * 1 ) fill the list with 0 , till n1 > 0 * 2 ) fill the list with 1 , till n2 > 0 * 3 ) fill the list with 2 , till n3 > 0 ; Inserts a new Node at front of the list . ; 1 & 2 : Allocate the Node & Put in the data ; 3. Make next of new Node as head ; 4. Move the head to point to new Node ; Function to print linked list ; Driver program to test above functions ; Constructed Linked List is 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 8 -> 9 -> null"
How can the above be solved in Java?

class LinkedList { Node head ; class Node { int data ; Node next ; Node ( int d ) { data = d ; next = null ; } } void sortList ( ) { int count [ ] = { 0 , 0 , 0 } ; Node ptr = head ; while ( ptr != null ) { count [ ptr . data ] ++ ; ptr = ptr . next ; } int i = 0 ; ptr = head ; while ( ptr != null ) { if ( count [ i ] == 0 ) i ++ ; else { ptr . data = i ; -- count [ i ] ; ptr = ptr . next ; } } } public void push ( int new_data ) { Node new_node = new Node ( new_data ) ; new_node . next = head ; head = new_node ; } void printList ( ) { Node temp = head ; while ( temp != null ) { System . out . print ( temp . data + " ▁ " ) ; temp = temp . next ; } System . out . println ( ) ; } public static void main ( String args [ ] ) { LinkedList llist = new LinkedList ( ) ; llist . push ( 0 ) ; llist . push ( 1 ) ; llist . push ( 0 ) ; llist . push ( 2 ) ; llist . push ( 1 ) ; llist . push ( 1 ) ; llist . push ( 2 ) ; llist . push ( 1 ) ; llist . push ( 2 ) ; System . out . println ( " Linked ▁ List ▁ before ▁ sorting " ) ; llist . printList ( ) ; llist . sortList ( ) ; System . out . println ( " Linked ▁ List ▁ after ▁ sorting " ) ; llist . printList ( ) ; } }


"Sort a nearly sorted array using STL | A STL based Java program to sort a nearly sorted array . ; Given an array of size n , where every element is k away from its target position , sorts the array in O ( n Log n ) time . ; Sort the array using inbuilt function ; An utility function to print array elements ; Driver code"
How can the above be solved in Java?

import java . util . * ; public class GFG { static void sortK ( int [ ] arr , int n , int k ) { Arrays . sort ( arr ) ; } static void printArray ( int [ ] arr , int size ) { for ( int i = 0 ; i < size ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( ) ; } public static void main ( String [ ] args ) { int k = 3 ; int [ ] arr = { 2 , 6 , 3 , 12 , 56 , 8 } ; int n = arr . length ; sortK ( arr , n , k ) ; System . out . println ( " Following ▁ is ▁ sorted ▁ array " ) ; printArray ( arr , n ) ; } }


"Sort a stream of integers | Java program for the above approach ; Function to sort a stream of integers ; Stores the position of array elements ; Traverse through the array ; If any element is found to be greater than the current element ; If an element > num is not present ; Otherwise , place the number at its right position ; Function to print the sorted stream of integers ; Stores the sorted stream of integers ; Traverse the array ; Function Call ; Print the array after every insertion ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void Sort ( Vector < Integer > ans , int num ) { int pos = - 1 ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) { if ( ans . get ( i ) >= num ) { pos = i ; break ; } } if ( pos == - 1 ) ans . add ( num ) ; else ans . add ( pos , num ) ; } static void sortStream ( int arr [ ] , int N ) { Vector < Integer > ans = new Vector < Integer > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Sort ( ans , arr [ i ] ) ; for ( int j = 0 ; j < ans . size ( ) ; j ++ ) { System . out . print ( ans . get ( j ) + " ▁ " ) ; } System . out . println ( ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 4 , 1 , 7 , 6 , 2 } ; int N = arr . length ; sortStream ( arr , N ) ; } }


"Sort a string according to the order defined by another string | Java program to sort a string according to the order defined by a pattern string ; Sort str according to the order defined by pattern . ; Create a count array stor count of characters in str . ; Count number of occurrences of each character in str . ; Traverse the pattern and print every characters same number of times as it appears in str . This loop takes O ( m + n ) time where m is length of pattern and n is length of str . ; Driver code"
How can the above be solved in Java?

class GFG { static int MAX_CHAR = 26 ; static void sortByPattern ( char [ ] str , char [ ] pat ) { int count [ ] = new int [ MAX_CHAR ] ; for ( int i = 0 ; i < str . length ; i ++ ) { count [ str [ i ] - ' a ' ] ++ ; } int index = 0 ; for ( int i = 0 ; i < pat . length ; i ++ ) { for ( int j = 0 ; j < count [ pat [ i ] - ' a ' ] ; j ++ ) { str [ index ++ ] = pat [ i ] ; } } } public static void main ( String args [ ] ) { char [ ] pat = " bca " . toCharArray ( ) ; char [ ] str = " abc " . toCharArray ( ) ; sortByPattern ( str , pat ) ; System . out . println ( String . valueOf ( str ) ) ; } }


"Sort a string lexicographically by reversing a substring | Java program for the above approach ; Function to find the substring in S required to be reversed ; Stores the size of the string ; Stores the starting point of the substring ; Iterate over the string S while i < N ; Increment the value of i ; Stores the ending index of the substring ; If start <= 0 or i >= N ; If start >= 1 and i <= N ; Return the boolean value ; If start >= 1 ; Return the boolean value ; If i < N ; Return true if S [ start ] is less than or equal to S [ i ] ; Otherwise ; Function to check if it is possible to sort the string or not ; Stores the starting and the ending index of substring ; Stores whether it is possible to sort the substring ; Traverse the range [ 1 , N ] ; If S [ i ] is less than S [ i - 1 ] ; If flag stores true ; If adjust ( S , i , start , end ) return false ; Print - 1 ; Unset the flag ; Otherwise ; Print - 1 ; If start is equal to - 1 ; Update start and end ; Print the value of start ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int i , start , end ; static boolean adjust ( String S ) { int N = S . length ( ) ; start = i - 1 ; while ( i < N && S . charAt ( i ) < S . charAt ( i - 1 ) ) { i ++ ; } end = i - 1 ; if ( start <= 0 && i >= N ) return true ; if ( start >= 1 && i <= N ) { return ( S . charAt ( end ) >= S . charAt ( start - 1 ) && S . charAt ( start ) <= S . charAt ( i ) ) ; } if ( start >= 1 ) { return S . charAt ( end ) >= S . charAt ( start - 1 ) ; } if ( i < N ) { return S . charAt ( start ) <= S . charAt ( i ) ; } return false ; } static void isPossible ( String S , int N ) { start = - 1 ; end = - 1 ; boolean flag = true ; for ( i = 1 ; i < N ; i ++ ) { if ( S . charAt ( i ) < S . charAt ( i - 1 ) ) { if ( flag ) { if ( adjust ( S ) == false ) { System . out . println ( - 1 ) ; return ; } flag = false ; } else { System . out . println ( - 1 ) ; return ; } } } if ( start == - 1 ) { start = end = 1 ; } System . out . println ( start + " ▁ " + end ) ; } public static void main ( String [ ] args ) { String S = " abcyxuz " ; int N = S . length ( ) ; isPossible ( S , N ) ; } }


"Sort a string without altering the position of vowels | Java program for the above approach ; Function to sort the string leaving the vowels unchanged ; Length of string S ; Traverse the string S ; Sort the string temp ; Pointer to traverse the sorted string of consonants ; Traverse the string S ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void sortStr ( String str ) { char S [ ] = str . toCharArray ( ) ; int N = S . length ; ArrayList < Character > temp = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] != ' a ' && S [ i ] != ' e ' && S [ i ] != ' i ' && S [ i ] != ' o ' && S [ i ] != ' u ' ) temp . add ( S [ i ] ) ; } if ( temp . size ( ) != 0 ) Collections . sort ( temp ) ; int ptr = 0 ; for ( int i = 0 ; i < N ; i ++ ) { if ( S [ i ] != ' a ' && S [ i ] != ' e ' && S [ i ] != ' i ' && S [ i ] != ' o ' && S [ i ] != ' u ' ) S [ i ] = temp . get ( ptr ++ ) ; } System . out . println ( new String ( S ) ) ; } public static void main ( String [ ] args ) { String S = " geeksforgeeks " ; sortStr ( S ) ; } }


"Sort all even numbers in ascending order and then sort all odd numbers in descending order | Java program sort array in even and odd manner . The odd numbers are to be sorted in descending order and the even numbers in ascending order ; To do two way sort . First sort even numbers in ascending order , then odd numbers in descending order . ; Make all odd numbers negative ; if ( ( arr [ i ] & 1 ) != 0 ) Check for odd ; Sort all numbers ; Retaining original array ; Driver Method"
How can the above be solved in Java?

import java . util . Arrays ; public class GFG { static void twoWaySort ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) arr [ i ] *= - 1 ; Arrays . sort ( arr ) ; for ( int i = 0 ; i < n ; i ++ ) if ( ( arr [ i ] & 1 ) != 0 ) arr [ i ] *= - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 3 , 2 , 7 , 5 , 4 } ; twoWaySort ( arr , arr . length ) ; System . out . println ( Arrays . toString ( arr ) ) ; } }


"Sort all special primes in their relative positions | Java implementation of the above approach ; Function for the Sieve of Eratosthenes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to sort the special primes in their relative positions ; Maximum element from the array ; prime [ i ] will be true if i is a prime ; To store the special primes from the array ; If current element is a special prime ; Add it to the ArrayList and set arr [ i ] to - 1 ; Sort the special primes ; Position of a special prime ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void sieveOfEratosthenes ( boolean prime [ ] , int n ) { prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } } static void sortSpecialPrimes ( int arr [ ] , int n ) { int maxVal = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; boolean [ ] prime = new boolean [ maxVal + 1 ] ; for ( int i = 0 ; i < prime . length ; i ++ ) prime [ i ] = true ; sieveOfEratosthenes ( prime , maxVal ) ; Vector < Integer > list = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] && prime [ arr [ i ] - 2 ] ) { list . add ( arr [ i ] ) ; arr [ i ] = - 1 ; } } Collections . sort ( list ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == - 1 ) System . out . print ( list . get ( j ++ ) + " ▁ " ) ; else System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 31 , 5 , 2 , 1 , 7 } ; int n = arr . length ; sortSpecialPrimes ( arr , n ) ; } }


"Sort an Array based on the absolute difference of adjacent elements | Java implementation of the above approach ; Function that arrange the array such that all absolute difference between adjacent element are sorted ; To store the resultant array ; Sorting the given array in ascending order ; Variable to represent left and right ends of the given array ; Traversing the answer array in reverse order and arrange the array elements from arr [ ] in reverse order ; Inserting elements in zig - zag manner ; Displaying the resultant array ; Driver Code ; Function Call"
How can the above be solved in Java?

import java . util . * ; class GFG { static void sortedAdjacentDifferences ( int arr [ ] , int n ) { int [ ] ans = new int [ n ] ; Arrays . sort ( arr ) ; int l = 0 , r = n - 1 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( i % 2 == 1 ) { ans [ i ] = arr [ l ] ; l ++ ; } else { ans [ i ] = arr [ r ] ; r -- ; } } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( ans [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 5 , - 2 , 4 , 8 , 6 , 4 , 5 } ; int n = arr . length ; sortedAdjacentDifferences ( arr , n ) ; } }


"Sort an Array of Strings according to the number of Vowels in them | Java implementation of the approach ; Function to check the Vowel ; Returns count of vowels in str ; Check for vowel ; Function to sort the array according to the number of the vowels ; Vector to store the number of vowels with respective elements ; Inserting number of vowels with respective strings in the vector pair ; Sort the vector , this will sort the pair according to the number of vowels ; Print the sorted vector content ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; import java . io . * ; class GFG { static class pair { int first ; String second ; pair ( int first , String second ) { this . first = first ; this . second = second ; } } static boolean isVowel ( char ch ) { ch = Character . toUpperCase ( ch ) ; return ( ch == ' A ' ch == ' E ' ch == ' I ' ch == ' O ' ch == ' U ' ) ; } static int countVowels ( String str ) { int count = 0 ; for ( int i = 0 ; i < str . length ( ) ; i ++ ) if ( isVowel ( str . charAt ( i ) ) ) ++ count ; return count ; } static void sortArr ( String arr [ ] , int n ) { ArrayList < pair > vp = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { vp . add ( new pair ( countVowels ( arr [ i ] ) , arr [ i ] ) ) ; } Collections . sort ( vp , ( a , b ) -> a . first - b . first ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) System . out . print ( vp . get ( i ) . second + " ▁ " ) ; } public static void main ( String [ ] args ) { String arr [ ] = { " lmno " , " pqrst " , " aeiou " , " xyz " } ; int n = arr . length ; sortArr ( arr , n ) ; } }


"Sort an Array of dates in ascending order using Custom Comparator | Java implementation to sort the array of dates in the form of " DD - MM - YYYY " using custom comparator ; Condition to check the year ; Condition to check the month ; Condition to check the day ; Function that prints the dates in ascensding order ; Sort the dates using library sort function with custom Comparator ; Loop to print the dates ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { if ( year2 . compareTo ( year1 ) > 0 ) return - 1 ; else if ( year2 . compareTo ( year1 ) < 0 ) return 1 ; else if ( month2 . compareTo ( month1 ) > 0 ) return - 1 ; else if ( month2 . compareTo ( month1 ) < 0 ) return 1 ; else if ( day2 . compareTo ( day1 ) > 0 ) return - 1 ; else return 1 ; } } ) ; static void printDatesAscending ( ArrayList < String > arr ) { Collections . sort ( arr , new Comparator < > ( ) { public int compare ( String date1 , String date2 ) { String day1 = date1 . substring ( 0 , 2 ) ; String month1 = date1 . substring ( 3 , 5 ) ; String year1 = date1 . substring ( 6 ) ; String day2 = date2 . substring ( 0 , 2 ) ; String month2 = date2 . substring ( 3 , 5 ) ; String year2 = date2 . substring ( 6 ) ; for ( int i = 0 ; i < arr . size ( ) ; i ++ ) System . out . println ( arr . get ( i ) ) ; } public static void main ( String [ ] args ) { ArrayList < String > arr = new ArrayList < > ( ) ; arr . add ( "25-08-1996" ) ; arr . add ( "03-08-1970" ) ; arr . add ( "09-04-1994" ) ; arr . add ( "29-08-1996" ) ; arr . add ( "14-02-1972" ) ; printDatesAscending ( arr ) ; } }


"Sort an almost sorted array where only two elements are swapped | Java program to sort using one swap ; This function sorts an array that can be sorted by single swap ; Traverse the given array from rightmost side ; Check if arr [ i ] is not in order ; Find the other element to be swapped with arr [ i ] ; Swap the pair ; A utility function to print an array of size n ; Driver Code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void sortByOneSwap ( int arr [ ] , int n ) { for ( int i = n - 1 ; i > 0 ; i -- ) { if ( arr [ i ] < arr [ i - 1 ] ) { int j = i - 1 ; while ( j >= 0 && arr [ i ] < arr [ j ] ) j -- ; int temp = arr [ i ] ; arr [ i ] = arr [ j + 1 ] ; arr [ j + 1 ] = temp ; break ; } } } static void printArray ( int arr [ ] , int n ) { int i ; for ( i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 30 , 20 , 40 , 50 , 60 , 70 } ; int n = arr . length ; System . out . println ( " Given ▁ array ▁ is ▁ " ) ; printArray ( arr , n ) ; sortByOneSwap ( arr , n ) ; System . out . println ( " Sorted ▁ array ▁ is ▁ " ) ; printArray ( arr , n ) ; } }


"Sort an alphanumeric string such that the positions of alphabets and numbers remain unchanged | A Java implementation of the approach ; Function that returns the string s in sorted form such that the positions of alphabets and numeric digits remain unchanged ; String to character array ; Sort the array ; Count of alphabets and numbers ; Get the index from where the alphabets start ; Now replace the string with sorted string ; If the position was occupied by an alphabet then replace it with alphabet ; Else replace it with a number ; Return the sorted string ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static String sort ( String s ) { char [ ] c = new char [ s . length ( ) + 1 ] ; c = s . toCharArray ( ) ; Arrays . sort ( c ) ; int al_c = 0 , nu_c = 0 ; while ( c [ al_c ] < 97 ) al_c ++ ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { if ( s . charAt ( i ) < 97 ) s = s . substring ( 0 , i ) + c [ nu_c ++ ] + s . substring ( i + 1 ) ; else s = s . substring ( 0 , i ) + c [ al_c ++ ] + s . substring ( i + 1 ) ; } return s ; } public static void main ( String [ ] args ) { String s = " d4c3b2a1" ; System . out . println ( sort ( s ) ) ; } }


"Sort an array according to absolute difference with a given value " using ▁ constant ▁ extra ▁ space " | Java program to sort an array based on absolute difference with a given value x . ; Below lines are similar to insertion sort ; Insert arr [ i ] at correct place ; Function to print the array ; Driver code"
How can the above be solved in Java?

class GFG { static void arrange ( int arr [ ] , int n , int x ) { for ( int i = 1 ; i < n ; i ++ ) { int diff = Math . abs ( arr [ i ] - x ) ; int j = i - 1 ; if ( Math . abs ( arr [ j ] - x ) > diff ) { int temp = arr [ i ] ; while ( j >= 0 && Math . abs ( arr [ j ] - x ) > diff ) { arr [ j + 1 ] = arr [ j ] ; j -- ; } arr [ j + 1 ] = temp ; } } } static void print ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 5 , 3 , 9 , 2 } ; int n = arr . length ; int x = 7 ; arrange ( arr , n , x ) ; print ( arr , n ) ; } }


"Sort an array according to absolute difference with given value | Java program to sort an array according absolute difference with x . ; Function to sort an array according absolute difference with x . ; Store values in a map with the difference with X as key ; Update the values of array ; Function to print the array ; Driver code"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void rearrange ( int [ ] arr , int n , int x ) { TreeMap < Integer , ArrayList < Integer > > m = new TreeMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int diff = Math . abs ( x - arr [ i ] ) ; if ( m . containsKey ( diff ) ) { ArrayList < Integer > al = m . get ( diff ) ; al . add ( arr [ i ] ) ; m . put ( diff , al ) ; } else { ArrayList < Integer > al = new ArrayList < > ( ) ; al . add ( arr [ i ] ) ; m . put ( diff , al ) ; } } int index = 0 ; for ( Map . Entry entry : m . entrySet ( ) ) { ArrayList < Integer > al = m . get ( entry . getKey ( ) ) ; for ( int i = 0 ; i < al . size ( ) ; i ++ ) arr [ index ++ ] = al . get ( i ) ; } } static void printArray ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String args [ ] ) { int [ ] arr = { 10 , 5 , 3 , 9 , 2 } ; int n = arr . length ; int x = 7 ; rearrange ( arr , n , x ) ; printArray ( arr , n ) ; } }


"Sort an array by left shifting digits of array elements | Java program for the above approach ; Function to check if an array is sorted in increasing order or not ; Traverse the array ; Function to sort the array by left shifting digits of array elements ; Stores previous array element ; Traverse the array arr [ ] ; Stores current element ; Stores current element in String format ; Left - shift digits of current element in all possible ways ; Left - shift digits of current element by idx ; If temp greater than or equal to prev and temp less than optEle ; Update arr [ i ] ; Update prev ; If arr is in increasing order ; Otherwise ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean isIncreasing ( int [ ] arr ) { for ( int i = 0 ; i < arr . length - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) return false ; } return true ; } static int [ ] sortArr ( int [ ] arr ) { int prev = - 1 ; for ( int i = 0 ; i < arr . length ; i ++ ) { int optEle = arr [ i ] ; String strEle = String . valueOf ( arr [ i ] ) ; for ( int idx = 0 ; idx < strEle . length ( ) ; idx ++ ) { String strEle2 = strEle . substring ( idx ) + strEle . substring ( 0 , idx ) ; int temp = Integer . valueOf ( strEle2 ) ; if ( temp >= prev && temp < optEle ) optEle = temp ; } arr [ i ] = optEle ; prev = arr [ i ] ; } if ( isIncreasing ( arr ) ) return arr ; else { return new int [ ] { - 1 } ; } } public static void main ( String [ ] args ) { int [ ] arr = { 511 , 321 , 323 , 432 , 433 } ; int [ ] res = sortArr ( arr ) ; for ( int i = 0 ; i < res . length ; i ++ ) System . out . print ( res [ i ] + " ▁ " ) ; } }


"Sort an array by swapping elements of different type specified by another array | Java program to check if it is possible to sort the array in non - decreasing order by swapping elements of different types ; Function to check if it is possible to sort the array in non - decreasing order by swapping elements of different types ; Consider the array to be already sorted ; Checking if array is already sorted ; Check for a pair which is in decreasing order ; Count the frequency of each type of element ; type0 stores count of elements of type 0 ; type1 stores count of elements of type 1 ; Return true if array is already sorted ; Return false if all elements are of same type and array is unsorted ; Possible for all other cases ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static boolean sorting_possible ( int a [ ] , int b [ ] , int n ) { boolean sorted = true ; int type1 = 0 , type0 = 0 , i ; for ( i = 1 ; i < n ; i ++ ) { if ( a [ i ] < a [ i - 1 ] ) { sorted = false ; break ; } } for ( i = 0 ; i < n ; i ++ ) { if ( b [ i ] == 0 ) type0 ++ ; else type1 ++ ; } if ( sorted ) return true ; else if ( type1 == n type0 == n ) return false ; else return true ; } public static void main ( String [ ] args ) { int a [ ] = { 15 , 1 , 2 , 17 , 6 } ; int b [ ] = { 1 , 1 , 0 , 1 , 1 } ; int n = a . length ; boolean res = sorting_possible ( a , b , n ) ; if ( res ) System . out . print ( " Yes " ) ; else System . out . print ( " No " ) ; } }


"Sort an array containing two types of elements | Java program to sort an array with two types of values in one traversal ; Method for segregation 0 and 1 given input array ; Driver program"
How can the above be solved in Java?

class segregation { static void segregate0and1 ( int arr [ ] , int n ) { int type0 = 0 ; int type1 = n - 1 ; while ( type0 < type1 ) { if ( arr [ type0 ] == 1 ) { arr [ type0 ] = arr [ type0 ] + arr [ type1 ] ; arr [ type1 ] = arr [ type0 ] - arr [ type1 ] ; arr [ type0 ] = arr [ type0 ] - arr [ type1 ] ; type1 -- ; } else { type0 ++ ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 1 , 1 , 0 , 1 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 0 , 0 } ; segregate0and1 ( arr , arr . length ) ; for ( int a : arr ) System . out . print ( a + " ▁ " ) ; } }


"Sort an array in increasing order of their Multiplicative Persistence | Java program for the above approach ; Function to find the number of steps required to reduce a given number to a single - digit number ; Stores the required result ; Iterate until a single digit number is not obtained ; Store the number in a temporary variable ; Iterate over all digits and store their product in num ; Increment the answer by 1 ; Return the result ; Count number of steps required to reduce X and Y into single digits integer ; Return true ; Function to sort the array according to the number of steps required to reduce a given number into a single digit number ; Sort the array using the comparator function ; Print the array after sorting ; Driver code ; Function Call"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int countReduction ( int num ) { int ans = 0 ; while ( num >= 10 ) { int temp = num ; num = 1 ; while ( temp > 0 ) { int digit = temp % 10 ; temp = temp / 10 ; num *= digit ; } ans ++ ; } return ans ; } int x1 = countReduction ( x ) ; int y1 = countReduction ( y ) ; if ( x1 < y1 ) return - 1 ; return 1 ; } } ) ; static void sortArray ( Integer a [ ] , int n ) { Arrays . sort ( a , new Comparator < Integer > ( ) { public int compare ( Integer x , Integer y ) { for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( a [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { Integer arr [ ] = { 39 , 999 , 4 , 9876 } ; int N = arr . length ; sortArray ( arr , N ) ; } }


"Sort an array in wave form | A O ( n ) Java program to sort an input array in wave form ; A utility method to swap two numbers . ; This function sorts arr [ 0. . n - 1 ] in wave form , i . e . , arr [ 0 ] >= arr [ 1 ] <= arr [ 2 ] >= arr [ 3 ] <= arr [ 4 ] ... . ; Traverse all even elements ; If current even element is smaller than previous ; If current even element is smaller than next ; Driver program to test above function"
How can the above be solved in Java?

class SortWave { void swap ( int arr [ ] , int a , int b ) { int temp = arr [ a ] ; arr [ a ] = arr [ b ] ; arr [ b ] = temp ; } void sortInWave ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i += 2 ) { if ( i > 0 && arr [ i - 1 ] > arr [ i ] ) swap ( arr , i - 1 , i ) ; if ( i < n - 1 && arr [ i ] < arr [ i + 1 ] ) swap ( arr , i , i + 1 ) ; } } public static void main ( String args [ ] ) { SortWave ob = new SortWave ( ) ; int arr [ ] = { 10 , 90 , 49 , 2 , 1 , 5 , 23 } ; int n = arr . length ; ob . sortInWave ( arr , n ) ; for ( int i : arr ) System . out . print ( i + " ▁ " ) ; } }


"Sort an array in wave form | Java implementation of naive method for sorting an array in wave form . ; A utility method to swap two numbers . ; This function sorts arr [ 0. . n - 1 ] in wave form , i . e . , arr [ 0 ] >= arr [ 1 ] <= arr [ 2 ] >= arr [ 3 ] <= arr [ 4 ] . . ; Sort the input array ; Swap adjacent elements ; Driver method"
How can the above be solved in Java?

import java . util . * ; class SortWave { void swap ( int arr [ ] , int a , int b ) { int temp = arr [ a ] ; arr [ a ] = arr [ b ] ; arr [ b ] = temp ; } void sortInWave ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; for ( int i = 0 ; i < n - 1 ; i += 2 ) swap ( arr , i , i + 1 ) ; } public static void main ( String args [ ] ) { SortWave ob = new SortWave ( ) ; int arr [ ] = { 10 , 90 , 49 , 2 , 1 , 5 , 23 } ; int n = arr . length ; ob . sortInWave ( arr , n ) ; for ( int i : arr ) System . out . print ( i + " ▁ " ) ; } }


"Sort an array of 0 s , 1 s , 2 s and 3 s | Java program for the above approach ; Function to sort the array having array element only 0 , 1 , 2 , and 3 ; Iterate until mid <= j ; If arr [ mid ] is 0 ; Swap integers at indices i and mid ; Increment i ; Increment mid ; Otherwise if the value of arr [ mid ] is 3 ; Swap arr [ mid ] and arr [ j ] ; Decrement j ; Otherwise if the value of arr [ mid ] is either 1 or 2 ; Increment the value of mid ; Iterate until i <= j ; If arr [ i ] the value of is 2 ; Swap arr [ i ] and arr [ j ] ; Decrement j ; Otherwise , increment i ; Print the sorted array arr [ ] ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static void sortArray ( int [ ] arr , int N ) { int i = 0 , j = N - 1 , mid = 0 ; while ( mid <= j ) { if ( arr [ mid ] == 0 ) { int temp = arr [ i ] ; arr [ i ] = arr [ mid ] ; arr [ mid ] = temp ; i ++ ; mid ++ ; } else if ( arr [ mid ] == 3 ) { int temp = arr [ mid ] ; arr [ mid ] = arr [ j ] ; arr [ j ] = temp ; j -- ; } else if ( arr [ mid ] == 1 arr [ mid ] == 2 ) { mid ++ ; } } while ( i <= j ) { if ( arr [ i ] == 2 ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; j -- ; } else { i ++ ; } } for ( int k = 0 ; k < N ; k ++ ) { System . out . print ( arr [ k ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 3 , 2 , 1 , 0 , 2 , 3 , 1 , 0 } ; int N = arr . length ; sortArray ( arr , N ) ; } }


"Sort an array of 0 s , 1 s and 2 s ( Simple Counting ) | Example input = [ 0 , 1 , 2 , 2 , 0 , 0 ] output = [ 0 , 0 , 0 , 1 , 2 , 2 ]"
How can the above be solved in Java?

import java . util . ArrayList ; import java . util . List ; class GFG { static int [ ] inputArray = { 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 } ; static List < Integer > outputArray = new ArrayList < > ( ) ; static int indexOfOne = 0 ; static void print ( ) { for ( int item : inputArray ) if ( item == 2 ) outputArray . add ( item ) ; else if ( item == 1 ) { outputArray . add ( indexOfOne , item ) ; indexOfOne += 1 ; } else if ( item == 0 ) { outputArray . add ( 0 , item ) ; indexOfOne += 1 ; } else { System . out . println ( " ▁ wrong ▁ value ▁ - ▁ Aborting ▁ " ) ; continue ; } } public static void main ( String [ ] args ) { print ( ) ; for ( int item : outputArray ) System . out . print ( item + " , ▁ " ) ; } }


"Sort an array of 0 s , 1 s and 2 s ( Simple Counting ) | Simple Java program to sort an array of 0 s 1 s and 2 s . ; Variables to maintain the count of 0 ' s , ▁ ▁ 1' s and 2 's in the array ; Putting the 0 's in the  array in starting. ; Putting the 1 ' s ▁ in ▁ the ▁ ▁ array ▁ after ▁ the ▁ 0' s . ; Putting the 2 ' s ▁ in ▁ the ▁ ▁ array ▁ after ▁ the ▁ 1' s ; Prints the array ; Driver function"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; public class GfG { public static void sort012 ( int arr [ ] , int n ) { int count0 = 0 , count1 = 0 ; int count2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 0 ) count0 ++ ; if ( arr [ i ] == 1 ) count1 ++ ; if ( arr [ i ] == 2 ) count2 ++ ; } for ( int i = 0 ; i < count0 ; i ++ ) arr [ i ] = 0 ; for ( int i = count0 ; i < ( count0 + count1 ) ; i ++ ) arr [ i ] = 1 ; for ( int i = ( count0 + count1 ) ; i < n ; i ++ ) arr [ i ] = 2 ; printArray ( arr , n ) ; } public static void printArray ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 } ; int n = 12 ; sort012 ( arr , n ) ; } }


"Sort an array of 0 s , 1 s and 2 s | Java implementation of the approach ; Utility function to print the contents of an array ; Function to sort the array of 0 s , 1 s and 2 s ; Count the number of 0 s , 1 s and 2 s in the array ; Update the array ; Store all the 0 s in the beginning ; Then all the 1 s ; Finally all the 2 s ; Print the sorted array ; Driver code"
How can the above be solved in Java?

import java . io . * ; class GFG { static void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void sortArr ( int arr [ ] , int n ) { int i , cnt0 = 0 , cnt1 = 0 , cnt2 = 0 ; for ( i = 0 ; i < n ; i ++ ) { switch ( arr [ i ] ) { case 0 : cnt0 ++ ; break ; case 1 : cnt1 ++ ; break ; case 2 : cnt2 ++ ; break ; } } i = 0 ; while ( cnt0 > 0 ) { arr [ i ++ ] = 0 ; cnt0 -- ; } while ( cnt1 > 0 ) { arr [ i ++ ] = 1 ; cnt1 -- ; } while ( cnt2 > 0 ) { arr [ i ++ ] = 2 ; cnt2 -- ; } printArr ( arr , n ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 } ; int n = arr . length ; sortArr ( arr , n ) ; } }


"Sort an array of 0 s , 1 s and 2 s | Java program to sort an array of 0 , 1 and 2 ; Sort the input array , the array is assumed to have values in { 0 , 1 , 2 } ; Utility function to print array arr [ ] ; Driver function to check for above functions"
How can the above be solved in Java?

import java . io . * ; class countzot { static void sort012 ( int a [ ] , int arr_size ) { int lo = 0 ; int hi = arr_size - 1 ; int mid = 0 , temp = 0 ; while ( mid <= hi ) { switch ( a [ mid ] ) { case 0 : { temp = a [ lo ] ; a [ lo ] = a [ mid ] ; a [ mid ] = temp ; lo ++ ; mid ++ ; break ; } case 1 : mid ++ ; break ; case 2 : { temp = a [ mid ] ; a [ mid ] = a [ hi ] ; a [ hi ] = temp ; hi -- ; break ; } } } } static void printArray ( int arr [ ] , int arr_size ) { int i ; for ( i = 0 ; i < arr_size ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( " " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 0 , 1 , 1 , 0 , 1 , 2 , 1 , 2 , 0 , 0 , 0 , 1 } ; int arr_size = arr . length ; sort012 ( arr , arr_size ) ; System . out . println ( " Array ▁ after ▁ seggregation ▁ " ) ; printArray ( arr , arr_size ) ; } }


"Sort an array of strings according to string lengths | Java program to sort an Array of Strings according to their lengths ; Function to Sort the array of string according to lengths . This function implements Insertion Sort . ; Insert s [ j ] at its correct position ; Function to print the sorted array of string ; Driver function ; Function to perform sorting ; Calling the function to print result"
How can the above be solved in Java?

import java . util . * ; class solution { static void sort ( String [ ] s , int n ) { for ( int i = 1 ; i < n ; i ++ ) { String temp = s [ i ] ; int j = i - 1 ; while ( j >= 0 && temp . length ( ) < s [ j ] . length ( ) ) { s [ j + 1 ] = s [ j ] ; j -- ; } s [ j + 1 ] = temp ; } } static void printArraystring ( String str [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( str [ i ] + " ▁ " ) ; } public static void main ( String args [ ] ) { String [ ] arr = { " GeeksforGeeks " , " I " , " from " , " am " } ; int n = arr . length ; sort ( arr , n ) ; printArraystring ( arr , n ) ; } }


"Sort an array using Bubble Sort without using loops | java program for the above approach ; Function to implement bubble sort without using loops ; Base Case : If array contains a single element ; Base Case : If array contains two elements ; Store the first two elements of the list in variables a and b ; Store remaining elements in the list bs ; Store the list after each recursive call ; If a < b ; Otherwise , if b >= a ; Recursively call for the list less than the last element and and return the newly formed list ; Driver Code ; Print the array"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static ArrayList < Integer > bubble_sort ( ArrayList < Integer > ar ) { if ( ar . size ( ) <= 1 ) return ar ; if ( ar . size ( ) == 2 ) { if ( ar . get ( 0 ) < ar . get ( 1 ) ) return ar ; else return new ArrayList < Integer > ( Arrays . asList ( ar . get ( 1 ) , ar . get ( 0 ) ) ) ; } int a = ar . get ( 0 ) ; int b = ar . get ( 1 ) ; ArrayList < Integer > bs = new ArrayList < > ( ) ; for ( int i = 2 ; i < ar . size ( ) ; i ++ ) bs . add ( ar . get ( i ) ) ; ArrayList < Integer > res = new ArrayList < > ( ) ; if ( a < b ) { ArrayList < Integer > temp1 = new ArrayList < > ( ) ; temp1 . add ( b ) ; for ( int i = 0 ; i < bs . size ( ) ; i ++ ) temp1 . add ( bs . get ( i ) ) ; ArrayList < Integer > v = bubble_sort ( temp1 ) ; v . add ( 0 , a ) ; res = v ; } else { ArrayList < Integer > temp1 = new ArrayList < > ( ) ; temp1 . add ( a ) ; for ( int i = 0 ; i < bs . size ( ) ; i ++ ) temp1 . add ( bs . get ( i ) ) ; ArrayList < Integer > v = bubble_sort ( temp1 ) ; v . add ( 0 , b ) ; res = v ; } ArrayList < Integer > pass = new ArrayList < > ( ) ; for ( int i = 0 ; i < res . size ( ) - 1 ; i ++ ) pass . add ( res . get ( i ) ) ; ArrayList < Integer > ans = bubble_sort ( pass ) ; ans . add ( res . get ( res . size ( ) - 1 ) ) ; return ans ; } public static void main ( String [ ] args ) { ArrayList < Integer > arr = new ArrayList < Integer > ( Arrays . asList ( 1 , 3 , 4 , 5 , 6 , 2 ) ) ; ArrayList < Integer > res = bubble_sort ( arr ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) System . out . print ( res . get ( i ) + " ▁ " ) ; } }


"Sort an array when two halves are sorted | Java program to Merge Two Sorted Halves Of Array Into Single Sorted Array ; Merge two sorted halves of Array into single sorted array ; int half_i = 0 ; starting index of second half ; Temp Array store sorted resultant array ; First Find the point where array is divide into two half ; If Given array is all - ready sorted ; Merge two sorted arrays in single sorted array ; Copy the remaining elements of A [ i to half_ ! ] ; Copy the remaining elements of A [ half_ ! to n ] ; Driver code ; Print sorted Array"
How can the above be solved in Java?

import java . io . * ; class GFG { static void mergeTwoHalf ( int [ ] A , int n ) { int i ; int [ ] temp = new int [ n ] ; for ( i = 0 ; i < n - 1 ; i ++ ) { if ( A [ i ] > A [ i + 1 ] ) { half_i = i + 1 ; break ; } } if ( half_i == 0 ) return ; i = 0 ; int j = half_i ; int k = 0 ; while ( i < half_i && j < n ) { if ( A [ i ] < A [ j ] ) temp [ k ++ ] = A [ i ++ ] ; else temp [ k ++ ] = A [ j ++ ] ; } while ( i < half_i ) temp [ k ++ ] = A [ i ++ ] ; while ( j < n ) temp [ k ++ ] = A [ j ++ ] ; for ( i = 0 ; i < n ; i ++ ) A [ i ] = temp [ i ] ; } static public void main ( String [ ] args ) { int [ ] A = { 2 , 3 , 8 , - 1 , 7 , 10 } ; int n = A . length ; mergeTwoHalf ( A , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( A [ i ] + " ▁ " ) ; } }


"Sort an array when two halves are sorted | Java program to Merge two sorted halves of array Into Single Sorted Array ; Sort the given array using sort STL ; Driver code ; Print sorted Array"
How can the above be solved in Java?

import java . io . * ; import java . util . * ; class GFG { static void mergeTwoHalf ( int [ ] A , int n ) { Arrays . sort ( A ) ; } static public void main ( String [ ] args ) { int [ ] A = { 2 , 3 , 8 , - 1 , 7 , 10 } ; int n = A . length ; mergeTwoHalf ( A , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( A [ i ] + " ▁ " ) ; } }


"Sort an array with swapping only with a special element is allowed | Java program to sort an array by moving one space around . ; n is total number of elements . index is index of 999 or space . k is number of elements yet to be sorted . ; print the sorted array when loop reaches the base case ; else if k > 0 and space is at 0 th index swap each number with space and store index at second last index ; if space is neither start of array nor last element of array and element before it greater than / the element next to space ; first swap space and element next to space in case of { 3 , 999 , 2 } make it { 3 , 2 , 999 } ; than swap space and greater element convert { 3 , 2 , 999 } to { 999 , 2 , 3 } ; Wrapper over sortRec . ; Find index of space ( or 999 ) ; Invalid input ; Driver code"
How can the above be solved in Java?

class GFG { static void sortRec ( int arr [ ] , int index , int k , int n ) { if ( k == 0 ) { for ( int i = 1 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( 999 ) ; return ; } else if ( k > 0 && index == 0 ) { index = n - 2 ; for ( int i = 1 ; i <= index ; i ++ ) { arr [ i - 1 ] = arr [ i ] ; } arr [ index ] = 999 ; } if ( index - 1 >= 0 && index + 1 < n && arr [ index - 1 ] > arr [ index + 1 ] ) { swap ( arr , index , index + 1 ) ; swap ( arr , index - 1 , index + 1 ) ; } else swap ( arr , index , index - 1 ) ; sortRec ( arr , index - 1 , k - 1 , n ) ; } static int [ ] swap ( int [ ] arr , int i , int j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } static void sort ( int arr [ ] , int n ) { int index = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == 999 ) { index = i ; break ; } } if ( index == - 1 ) return ; sortRec ( arr , index , n , n ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 999 , 1 } ; int n = arr . length ; sort ( arr , n ) ; } }


"Sort an array without changing position of negative numbers | Java implementation of the approach ; Function to sort the array such that negative values do not get affected ; Store all non - negative values ; Sort non - negative values ; If current element is non - negative then update it such that all the non - negative values are sorted ; Print the sorted array ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void sortArray ( int a [ ] , int n ) { Vector < Integer > ans = new Vector < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) ans . add ( a [ i ] ) ; } Collections . sort ( ans ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] >= 0 ) { a [ i ] = ans . get ( j ) ; j ++ ; } } for ( int i = 0 ; i < n ; i ++ ) System . out . print ( a [ i ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , - 6 , - 3 , 8 , 4 , 1 } ; int n = arr . length ; sortArray ( arr , n ) ; } }


"Sort array after converting elements to their squares | Java program to Sort square of the numbers of the array ; Function to sort an square array ; First convert each array elements into its square ; Sort an array using " inbuild ▁ sort ▁ function " in Arrays class . ; Driver program to test above function"
How can the above be solved in Java?

import java . util . * ; import java . io . * ; class GFG { public static void sortSquares ( int arr [ ] ) { int n = arr . length ; for ( int i = 0 ; i < n ; i ++ ) arr [ i ] = arr [ i ] * arr [ i ] ; Arrays . sort ( arr ) ; } public static void main ( String [ ] args ) { int arr [ ] = { - 6 , - 3 , - 1 , 2 , 4 , 5 } ; int n = arr . length ; System . out . println ( " Before ▁ sort ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; sortSquares ( arr ) ; System . out . println ( " " ) ; System . out . println ( " After ▁ Sort ▁ " ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Sort array of strings after sorting each string after removing characters whose frequencies are not a powers of 2 | Java program for the above approach ; Function to check if N is power of 2 or not ; Base Case ; Return true if N is power of 2 ; Function to print array of strings in ascending order ; Sort strings in ascending order ; Print the array ; Function to sort the strings after modifying each string according to the given conditions ; Store the frequency of each characters of the string ; Stores the required array of strings ; Traverse the array of strings ; Temporary string ; Stores frequency of each alphabet of the string ; Update frequency of S [ i ] [ j ] ; Traverse the map freq ; Check if the frequency of i . first is a power of 2 ; Update string st ; Clear the map ; Null string ; Sort the string in descending order ; Update res ; Print the array of strings ; Driver Code"
How can the above be solved in Java?

import java . io . * ; import java . lang . * ; import java . util . * ; class GFG { static boolean isPowerOfTwo ( int n ) { if ( n == 0 ) return false ; return ( Math . ceil ( Math . log ( n ) / Math . log ( 2 ) ) == Math . floor ( Math . log ( n ) / Math . log ( 2 ) ) ) ; } static void printArray ( ArrayList < String > res ) { Collections . sort ( res ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) { System . out . print ( res . get ( i ) + " ▁ " ) ; } } static void sortedStrings ( String S [ ] , int N ) { HashMap < Character , Integer > freq = new HashMap < > ( ) ; ArrayList < String > res = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { String st = " " ; for ( int j = 0 ; j < S [ i ] . length ( ) ; j ++ ) { freq . put ( S [ i ] . charAt ( j ) , freq . getOrDefault ( S [ i ] . charAt ( j ) , 0 ) + 1 ) ; } for ( char ch : freq . keySet ( ) ) { if ( isPowerOfTwo ( freq . get ( ch ) ) ) { for ( int j = 0 ; j < freq . get ( ch ) ; j ++ ) { st += ch ; } } } freq . clear ( ) ; if ( st . length ( ) == 0 ) continue ; char myCharArr [ ] = st . toCharArray ( ) ; Arrays . sort ( myCharArr ) ; String ns = " " ; for ( int j = myCharArr . length - 1 ; j >= 0 ; -- j ) ns += myCharArr [ j ] ; res . add ( ns ) ; } printArray ( res ) ; } public static void main ( String [ ] args ) { String arr [ ] = { " aaacbb " , " geeks " , " aaa " } ; int N = arr . length ; sortedStrings ( arr , N ) ; } }


"Sort elements by modulo with K | Java implementation of the approach ; Utility function to print the contents of an array ; Function to sort the array elements based on their modulo with K ; Create K empty vectors ; Update the vectors such that v [ i ] will contain all the elements that give remainder as i when divided by k ; Sorting all the vectors separately ; Replacing the elements in arr [ ] with the required modulo sorted elements ; Add all the elements of the current vector to the array ; Print the sorted array ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printArr ( int [ ] arr , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void sortWithRemainder ( int [ ] arr , int n , int k ) { ArrayList < ArrayList < Integer > > v = new ArrayList < ArrayList < Integer > > ( k ) ; for ( int i = 0 ; i < k ; i ++ ) v . add ( new ArrayList < Integer > ( ) ) ; for ( int i = 0 ; i < n ; i ++ ) { int t = arr [ i ] % k ; v . get ( t ) . add ( arr [ i ] ) ; } for ( int i = 0 ; i < k ; i ++ ) { Collections . sort ( v . get ( i ) ) ; } int j = 0 ; for ( int i = 0 ; i < k ; i ++ ) { for ( int x : v . get ( i ) ) { arr [ j ] = x ; j ++ ; } } printArr ( arr , n ) ; } public static void main ( String [ ] args ) { int [ ] arr = { 10 , 7 , 2 , 6 , 12 , 3 , 33 , 46 } ; int n = arr . length ; int k = 4 ; sortWithRemainder ( arr , n , k ) ; } }


"Sort elements of an array in increasing order of absolute difference of adjacent elements | Java implementation to sort the elements of the array in such a way that absolute difference between the adjacent elements are in increasing order ; Function to sort the elements of the array by difference ; Sorting the array ; Array to store the elements of the array ; Iterating over the length of the array to include each middle element of array ; Appending the middle element of the array ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void sortDiff ( Vector < Integer > arr , int n ) { Collections . sort ( arr ) ; Vector < Integer > out = new Vector < Integer > ( ) ; while ( n > 0 ) { out . add ( arr . get ( n / 2 ) ) ; arr . remove ( n / 2 ) ; n = n - 1 ; } for ( int i : out ) System . out . print ( i + " ▁ " ) ; } public static void main ( String [ ] args ) { Integer [ ] a = { 8 , 1 , 2 , 3 , 0 } ; Vector < Integer > arr = new Vector < Integer > ( Arrays . asList ( a ) ) ; int n = 5 ; sortDiff ( arr , n ) ; } }


"Sort elements of the array that occurs in between multiples of K | Java implementation of the approach ; Utility function to print the contents of an array ; Function to sort elements in between multiples of k ; To store the index of previous multiple of k ; If it is not the first multiple of k ; Sort the elements in between the previous and the current multiple of k ; Update previous to be current ; Print the updated array ; Driver code"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } static void sortArr ( int arr [ ] , int n , int k ) { int prev = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] % k == 0 ) { if ( prev != - 1 ) Arrays . sort ( arr , prev + 1 , i ) ; prev = i ; } } printArr ( arr , n ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 1 , 13 , 3 , 7 , 8 , 21 , 13 , 12 } ; int n = arr . length ; int k = 2 ; sortArr ( arr , n , k ) ; } }


"Sort elements on the basis of number of factors | Java implementation to sort numbers on the basis of factors ; each element having its index in the input array and number of factors ; method to count factors for a given number n ; if the number is a perfect square ; count all other factors ; if i is a factor then n / i will be another factor . So increment by 2 ; function to print numbers after sorting them in decreasing order of number of factors ; for each element of input array create a structure element to store its index and factors count ; sort the array of structures as defined ; compare method for the elements of the structure ; if two elements have the same number of factors then sort them in increasing order of their index in the input array ; sort in decreasing order of number of factors ; access index from the structure element and corresponding to that index access the element from arr ; Driver program to test above"
How can the above be solved in Java?

import java . util . Arrays ; import java . util . Comparator ; class Element { int index , no_of_fact ; public Element ( int i , int countFactors ) { index = i ; no_of_fact = countFactors ; } static int countFactors ( int n ) { int count = 0 ; int sq = ( int ) Math . sqrt ( n ) ; if ( sq * sq == n ) count ++ ; for ( int i = 1 ; i < Math . sqrt ( n ) ; i ++ ) { if ( n % i == 0 ) count += 2 ; } return count ; } static void printOnBasisOfFactors ( int arr [ ] , int n ) { Element num [ ] = new Element [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { num [ i ] = new Element ( i , countFactors ( arr [ i ] ) ) ; } Arrays . sort ( num , new Comparator < Element > ( ) { @ Override public int compare ( Element e1 , Element e2 ) { if ( e1 . no_of_fact == e2 . no_of_fact ) return e1 . index < e2 . index ? - 1 : 1 ; return e1 . no_of_fact > e2 . no_of_fact ? - 1 : 1 ; } } ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ num [ i ] . index ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 11 , 10 , 20 , 9 , 16 , 23 } ; printOnBasisOfFactors ( arr , arr . length ) ; } }


"Sort even and odd placed elements in increasing order | Java implementation of the approach ; function to print the odd and even indexed digits ; lists to store the odd and even positioned digits ; traverse through all the indexes in the integer ; if the digit is in odd_index position append it to odd_position list ; else append it to the even_position list ; print the elements in the list in sorted order ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void odd_even ( int arr [ ] , int n ) { Vector < Integer > odd_indexes = new Vector < Integer > ( ) ; Vector < Integer > even_indexes = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) odd_indexes . add ( arr [ i ] ) ; else even_indexes . add ( arr [ i ] ) ; } Collections . sort ( odd_indexes ) ; Collections . sort ( even_indexes ) ; for ( int i = 0 ; i < odd_indexes . size ( ) ; i ++ ) System . out . print ( odd_indexes . get ( i ) + " ▁ " ) ; for ( int i = 0 ; i < even_indexes . size ( ) ; i ++ ) System . out . print ( even_indexes . get ( i ) + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 2 , 7 , 6 , 8 } ; int n = arr . length ; odd_even ( arr , n ) ; } }


"Sort even | Java Program to separately sort even - placed and odd placed numbers and place them together in sorted array . ; create evenArr [ ] and oddArr [ ] ; Put elements in oddArr [ ] and evenArr [ ] as per their position ; sort evenArr [ ] in ascending order sort oddArr [ ] in descending order ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void bitonicGenerator ( int arr [ ] , int n ) { Vector < Integer > evenArr = new Vector < Integer > ( ) ; Vector < Integer > oddArr = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i % 2 != 1 ) { evenArr . add ( arr [ i ] ) ; } else { oddArr . add ( arr [ i ] ) ; } } Collections . sort ( evenArr ) ; Collections . sort ( oddArr , Collections . reverseOrder ( ) ) ; int i = 0 ; for ( int j = 0 ; j < evenArr . size ( ) ; j ++ ) { arr [ i ++ ] = evenArr . get ( j ) ; } for ( int j = 0 ; j < oddArr . size ( ) ; j ++ ) { arr [ i ++ ] = oddArr . get ( j ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 } ; int n = arr . length ; bitonicGenerator ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } }


"Sort even | Program to sort even - placed elements in increasing and odd - placed in decreasing order with constant space complexity ; first odd index ; last index ; if last index is odd ; decrement j to even index ; swapping till half of array ; Sort first half in increasing ; Sort second half in decreasing ; Reverse the second half ; Driver Program"
How can the above be solved in Java?

import java . util . Arrays ; class GFG { static void bitonicGenerator ( int arr [ ] , int n ) { int i = 1 ; int j = n - 1 ; if ( j % 2 != 0 ) j -- ; while ( i < j ) { arr = swap ( arr , i , j ) ; i += 2 ; j -= 2 ; } Arrays . sort ( arr , 0 , ( n + 1 ) / 2 ) ; Arrays . sort ( arr , ( n + 1 ) / 2 , n ) ; int low = ( n + 1 ) / 2 , high = n - 1 ; while ( low < high ) { Integer temp = arr [ low ] ; arr [ low ] = arr [ high ] ; arr [ high ] = temp ; low ++ ; high -- ; } } static int [ ] swap ( int [ ] arr , int i , int j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; return arr ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 } ; int n = arr . length ; bitonicGenerator ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } }


"Sort first half in ascending and second half in descending order | 1 | Java program to print first half in ascending order and the second half in descending order ; function to print half of the array in ascending order and the other half in descending order ; sorting the array ; printing first half in ascending order ; printing second half in descending order ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printOrder ( int [ ] arr , int n ) { Arrays . sort ( arr ) ; for ( int i = 0 ; i < n / 2 ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } for ( int j = n - 1 ; j >= n / 2 ; j -- ) { System . out . print ( arr [ j ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 5 , 4 , 6 , 2 , 1 , 3 , 8 , - 1 } ; int n = arr . length ; printOrder ( arr , n ) ; } }


"Sort first k values in ascending order and remaining n | Java program to sort first k elements in increasing order and remaining n - k elements in decreasing ; function to print half of the array in ascending order and the other half in descending order ; Store the k elements in an array ; Store the remaining n - k elements in an array ; sorting the array from 0 to k - 1 places ; sorting the array from k to n places ; storing the values in the final array arr ; printing the array ; Driver code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void printOrder ( int [ ] arr , int n , int k ) { int len1 = k , len2 = n - k ; int [ ] arr1 = new int [ k ] ; int [ ] arr2 = new int [ n - k ] ; for ( int i = 0 ; i < k ; i ++ ) arr1 [ i ] = arr [ i ] ; for ( int i = k ; i < n ; i ++ ) arr2 [ i - k ] = arr [ i ] ; Arrays . sort ( arr1 , 0 , k ) ; Arrays . sort ( arr2 , k , n - k ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( i < k ) arr [ i ] = arr1 [ i ] ; else { arr [ i ] = arr2 [ len2 - 1 ] ; len2 -- ; } } for ( int i = 0 ; i < n ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 5 , 4 , 6 , 2 , 1 , 3 , 8 , 9 , - 1 } ; int k = 4 ; int n = arr . length ; printOrder ( arr , n , k ) ; } }


"Sort first k values in ascending order and remaining n | Java program to sort first k elements in increasing order and remaining n - k elements in decreasing ; function to sort the array ; Sort first k elements in ascending order ; Sort remaining n - k elements in descending order ; Driver code ; Our arr contains 8 elements"
How can the above be solved in Java?

import java . util . * ; public class SortExample { static void printOrder ( Integer [ ] arr , int k ) { int n = arr . length ; Arrays . sort ( arr , 0 , k ) ; Arrays . sort ( arr , k , n , Collections . reverseOrder ( ) ) ; } public static void main ( String [ ] args ) { Integer [ ] arr = { 5 , 4 , 6 , 2 , 1 , 3 , 8 , 9 , - 1 } ; int k = 4 ; printOrder ( arr , k ) ; System . out . printf ( " % s " , Arrays . toString ( arr ) ) ; } }


"Sort given array to descending | Java program to implement the above approach ; Function to sort first K array elements in descending and last N - K in ascending order ; Sort the array in descending order ; Sort last ( N - K ) array elements in ascending order ; Print array elements ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { static void sortArrayInDescAsc ( int arr [ ] , int N , int K ) { Arrays . sort ( arr ) ; for ( int i = 0 , j = N - 1 ; i < N / 2 ; i ++ ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; j -- ; } Arrays . sort ( arr , K , N ) ; for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 7 , 6 , 8 , 9 , 0 , 1 , 2 , 2 , 1 , 8 , 9 , 6 , 7 } ; int N = arr . length ; int K = 6 ; sortArrayInDescAsc ( arr , N , K ) ; } }


"Sort integers in array according to their distance from the element K | Java implementation to Sort the integers in array according to their distance from given element K present in the array ; Function to get sorted array based on their distance from given integer K ; Vector to store respective elements with their distance from integer K ; Find the position of integer K ; Insert the elements with their distance from K in vector ; Element at distance 0 ; Elements at left side of K ; Elements at right side of K ; Print the vector content in sorted order ; Sort elements at same distance ; Print elements at distance i from K ; Driver Code"
How can the above be solved in Java?

import java . util . * ; class GFG { @ SuppressWarnings ( " unchecked " ) static void distanceSort ( int arr [ ] , int K , int n ) { Vector vd [ ] = new Vector [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { vd [ i ] = new Vector ( ) ; } int pos = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == K ) { pos = i ; break ; } } int i = pos - 1 , j = pos + 1 ; vd [ 0 ] . add ( arr [ pos ] ) ; while ( i >= 0 ) { vd [ pos - i ] . add ( arr [ i ] ) ; -- i ; } while ( j < n ) { vd [ j - pos ] . add ( arr [ j ] ) ; ++ j ; } for ( i = 0 ; i <= Math . max ( pos , n - pos - 1 ) ; ++ i ) { Collections . sort ( vd [ i ] ) ; for ( j = 0 ; j < vd [ i ] . size ( ) ; j ++ ) { int element = ( int ) vd [ i ] . get ( j ) ; System . out . print ( element + " ▁ " ) ; } } } public static void main ( String s [ ] ) { int arr [ ] = { 14 , 1101 , 10 , 35 , 0 } ; int K = 35 ; int n = arr . length ; distanceSort ( arr , K , n ) ; } }


"Sort n numbers in range from 0 to n ^ 2 | Java program to sort an array of size n where elements are in range from 0 to n ^ 2 1. ; A function to do counting sort of arr [ ] according to the digit represented by exp . ; output array ; Store count of occurrences in count [ ] ; Change count [ i ] so that count [ i ] now contains actual position of this digit in output [ ] ; Build the output array ; Copy the output array to arr [ ] , so that arr [ ] now contains sorted numbers according to current digit ; The main function to that sorts arr [ ] of size n using Radix Sort ; Do counting sort for first digit in base n . Note that instead of passing digit number , exp ( n ^ 0 = 1 ) is passed . ; Do counting sort for second digit in base n . Note that instead of passing digit number , exp ( n ^ 1 = n ) is passed . ; A utility function to print an array ; Driver program to test above functions ; Since array size is 7 , elements should be from 0 to 48"
How can the above be solved in Java?

class Sort1ToN2 { void countSort ( int arr [ ] , int n , int exp ) { int output [ ] = new int [ n ] ; int i , count [ ] = new int [ n ] ; for ( i = 0 ; i < n ; i ++ ) count [ i ] = 0 ; for ( i = 0 ; i < n ; i ++ ) count [ ( arr [ i ] / exp ) % n ] ++ ; for ( i = 1 ; i < n ; i ++ ) count [ i ] += count [ i - 1 ] ; for ( i = n - 1 ; i >= 0 ; i -- ) { output [ count [ ( arr [ i ] / exp ) % n ] - 1 ] = arr [ i ] ; count [ ( arr [ i ] / exp ) % n ] -- ; } for ( i = 0 ; i < n ; i ++ ) arr [ i ] = output [ i ] ; } void sort ( int arr [ ] , int n ) { countSort ( arr , n , 1 ) ; countSort ( arr , n , n ) ; } void printArr ( int arr [ ] , int n ) { for ( int i = 0 ; i < n ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String args [ ] ) { Sort1ToN2 ob = new Sort1ToN2 ( ) ; int arr [ ] = { 40 , 12 , 45 , 32 , 33 , 1 , 22 } ; int n = arr . length ; System . out . println ( " Given ▁ array " ) ; ob . printArr ( arr , n ) ; ob . sort ( arr , n ) ; System . out . println ( " Sorted ▁ array " ) ; ob . printArr ( arr , n ) ; } }


"Sort numbers based on count of letters required to represent them in words | Java program to sort the strings based on the numbers of letters required to represent them ; letters [ i ] stores the count of letters required to represent the digit i ; Function to return the sum of letters required to represent N ; Function to sort the array according to the sum of letters to represent n ; Vector to store the digit sum with respective elements ; Inserting digit sum with elements in the vector pair ; Making the vector pair ; Sort the vector , this will sort the pair according to the sum of letters to represent n ; Print the sorted vector content ; Driver code"
How can the above be solved in Java?

import java . util . * ; import java . lang . * ; class GFG { static int letters [ ] = { 4 , 3 , 3 , 3 , 4 , 4 , 3 , 5 , 5 , 4 } ; static int sumOfLetters ( int n ) { int sum = 0 ; while ( n > 0 ) { sum += letters [ n % 10 ] ; n = n / 10 ; } return sum ; } static void sortArr ( int arr [ ] , int n ) { ArrayList < int [ ] > vp = new ArrayList < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { vp . add ( new int [ ] { sumOfLetters ( arr [ i ] ) , arr [ i ] } ) ; } Collections . sort ( vp , ( a , b ) -> a [ 0 ] - b [ 0 ] ) ; for ( int i = 0 ; i < vp . size ( ) ; i ++ ) System . out . print ( vp . get ( i ) [ 1 ] + " ▁ " ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 12 , 10 , 31 , 18 } ; int n = arr . length ; sortArr ( arr , n ) ; } }