Accio Sort in java

Accio Sort in java

You’re given a statement in the form of a string ‘str’ that has no more than 9 words, with each word suffixed by a unique number ranging from 1 to N, where N is the total number of words in the sentence. Your goal is to reorder the words in ‘str’ according to their suffix numbers and return the string.

For Example

You are given ‘str’ = ‘yash1 accio3 jobs2’, in this we can see the ordering of the words like ‘yash’, ‘accio’ ‘jobs’ according to the suffix number. Hence the answer string is ‘yash jobs accio’.

Input Format

The only line of input contains a string ‘str’ representing the given string.

Output Format

The only line of output contains the sorted string.

Example 1

Input

yash1 accio3 jobs2

Output

yash jobs accio

Explanation

Refer problem statement for explanation.

Example 2

Input

hello2 hi1

Output

hi hello

Explanation

Since, hi has lower suffix than hello. So, hi will come before hello in output.

Constraints:

1 <= N <= 9

1 <= |str| <= 10 ^ 6

‘str’ will contain lower case characters of the English alphabet and each word will contain a number between 1 and N as suffix where N is number of words which are no more than 9.

Solution of Accio Sort in java:–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      String str = sc.nextLine();
      
      String s[] = str.split(" ");
      int arr[] = new int[s.length];

      //inserting suffix index into new array
      for(int i=0;i<s.length;i++)
        {
           int temp=s[i].length();
           int demo= Character.getNumericValue(s[i].charAt(temp-1));
           if(demo!=-1)
           {
             arr[i]=demo;
           }
        }
    

      for(int i=0;i<s.length;i++)
        {
           for(int j=0;j<s.length-1-i;j++)
             {
               if(arr[j]>arr[j+1])
               {
                 //sorting the string by suffix index
                 String temp=s[j];
                 s[j]=s[j+1];
                 s[j+1]=temp;

                 //after first iteration we are sorting index array
                 int suffle=arr[j];
                 arr[j]=arr[j+1];
                 arr[j+1]=suffle;
               }
             }
        }

      //printing the sorted string array without suffix index
      for(int i=0;i<s.length;i++)
        {
          System.out.print(s[i].substring(0,s[i].length()-1)+" ");
        }
	}
}

Add a Comment

Your email address will not be published. Required fields are marked *