Sort Mixed (Numeric First)
JavaScript
Medium
5 views
Problem Description
You get n tokens (strings). If a token is a valid finite number, treat it as numeric. Sort numeric tokens by numeric value. Non-numeric tokens come later sorted lexicographically. Print the final list.
Input Format
Line1: n. Line2: n tokens.
Output Format
One line sorted tokens.
Sample Test Case
Input:
7
10 2 abc -1 2.5 NaN z
Output:
-1 2 2.5 10 abc NaN z
Official Solution
const fs=require('fs');const raw=fs.readFileSync(0,'utf8').trim();if(!raw)process.exit(0);const a=raw.split(/\\s+/);let i=0;const n=Number(a[i++]);let tok=a.slice(i,i+n);const isNum=s=>{const v=Number(s);return Number.isFinite(v);};let num=[],str=[];for(const s of tok){if(isNum(s))num.push(s);else str.push(s);}num.sort((x,y)=>Number(x)-Number(y)||x.localeCompare(y));str.sort((x,y)=>x.localeCompare(y));process.stdout.write(num.concat(str).join(' '));
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!