Java Programming for sorting an array -


i have attended interview yesterday, don't find solution of given problem below. how sort int array starting 3 digits numbers , remaining 2,1,4,5 etc digits.

ex:-input

i={1,34,323,456,5432,34566,33,45,654} 

output is,

i={323,456,654,1,34,33,45,5432} 

i assumed 1 might wish alter order of number of digits, , allow them specified in order. have "sort" array corresponds number of digits should processed. assumed 1 should sort values in increasing order within final array. thought sorting part of experiment, did not use arrays.sort.

here take on approach:

public static void main(string[] args) {     int[] arr = {1,34,323,456,5432,34566,33,45,654};     int[] sort = {3, 2, 1, 4, 5 };      int lastpos = 0;     int looppos = 0;     int[] output = new int[arr.length];     // process whole array     (int s = 0; s < sort.length; ++s) {         string fmt = string.format("^[0-9]{%d}$", sort[s]);         pattern pat = pattern.compile(fmt);                      // set end of current location         looppos = lastpos;         (int = 0; < arr.length; ++i) {             int val = arr[i];             matcher m = pat.matcher(integer.tostring(val));             if (m.matches()) {                 // start @ beginning of looppos                 // continue until lastpos                 if (lastpos == looppos) {                     output[lastpos++] = val;                 }                 else {                     (int ins = looppos; ins < lastpos; ++ins) {                         int atpos = output[ins];                         // if smaller, must insert before                         if (val <= atpos) {                             (int rev = lastpos; rev > looppos; --rev) {                                 output[rev] = output[rev - 1];                             }                             output[ins] = val;                             ++lastpos;                             break;                         }                         else if (val > atpos) {                             output[lastpos++] = val;                             break;                         }                     }                 }              }         } //i     } //s      system.out.println(arrays.tostring(output)); } 

sample result:

[323, 456, 654, 33, 34, 45, 1, 5432, 34566]


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -