3

How would I sort arrays as follows:

[10, 7, 12, 3, 5, 6] --> [10, 12, 3, 5, 6, 7]

[12, 8, 5, 9, 6, 10] --> [12, 5, 6, 8, 9, 10] 
  • keeping array[0] in place
  • with the next highest integer(s) following (if there are any)
  • then ascending from the lowest integer
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
jmk
  • 466
  • 1
  • 4
  • 21

6 Answers6

10

You could save the value of the first element and use it in a condition for the first sorting delta. Then sort by the standard delta.

How it works (the sort order is from Edge)

              condition  numerical     sortFn
   a      b       delta      delta     result  comment
-----  -----  ---------  ---------  ---------  -----------------
   7     10*          1                     1  different section
  12*     7          -1                    -1  different section
  12*    10*          0          2          2  same section
  12*     7          -1                    -1  same section
   3      7           0         -4         -4  same section
   3     12*          1                     1  different section
   3      7           0         -4         -4  same section
   5      7           0         -2         -2  same section
   5     12*          1                     1  different section
   5      3           0          2          2  same section
   5      7           0         -2         -2  same section
   6      7           0         -1         -1  same section
   6      3           0          3          3  same section
   6      5           0          1          1  same section
   6      7           0         -1         -1  same section

* denotes elements who should be in the first section

Elements of different section means one of the elements goes into the first and the other into the second section, the value is taken by the delta of the condition.

Elements of the same section means, both elements belongs to the same section. For sorting the delta of the values is returned.

function sort(array) {
    var first = array[0];
    array.sort(function (a, b) {
       return (a < first) - (b < first) || a - b;
    });
    return array;
}

console.log(sort([10, 7, 12, 3, 5, 6]));
console.log(sort([12, 8, 5, 9, 6, 10]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

An easy solution could be to sort the entire array and then partition the resulting array on basis of your initial first element.

I.e.

  • first sort [10, 7, 12, 3] to [3, 7, 10, 12]
  • then split it into >= 10 and < 10: [10, 12] and [3, 7]
  • and finally combine both to [10, 12, 3, 7]

Sample implementation without polish:

function customSort(input) {
  var firstElem = input[0];
  var sortedInput = input.sort(function(a, b) { return a-b; });
  var firstElemPos = sortedInput.indexOf(firstElem);
  var greaterEqualsFirstElem = sortedInput.splice(firstElemPos);
  var lessThanFirstElem = sortedInput.splice(0, firstElemPos);
  return greaterEqualsFirstElem.concat(lessThanFirstElem);
}

console.log(customSort([10, 7, 12, 3, 5, 6]));
console.log(customSort([12, 8, 5, 9, 6, 10]));
console.log(customSort([12, 8, 5, 9, 12, 6, 10]));
console.log(customSort([12]));
console.log(customSort([]));
Marvin
  • 13,325
  • 3
  • 51
  • 57
  • 1
    Well... twice. There's certainly room for improvement, but probably at the cost of some comprehensibility (which was my primary goal). I personally find your solution more elegant, though. – Marvin Jun 08 '17 at 18:13
1

Have a look at below snippet.

It is really simple. Just remove first element from the arrary into new array.

Sort rest of the array and check if max of this array is greater than first element.

If yes, then push it into to result arrary. Otherwise concat rest of the array with result array

var input1 = [10, 7, 12, 3, 5, 6];
var expected1 = [10, 12, 3, 5, 6, 7];

var input2 = [12, 8, 5, 9, 6, 10];
var expected2 = [12, 5, 6, 8, 9, 10];

function customSort(aInput) {
  var aResult = [aInput.shift()];
  aInput = aInput.sort(function(a, b) { return a - b;});
  if (aInput[aInput.length - 1] > aResult[0]) {
    var iMax = aInput.pop();
    aResult.push(iMax);
  }
  aResult = aResult.concat(aInput);
  return aResult;
}

console.log("Expected: ", expected1.toString());
console.log("Sorted: ", customSort(input1).toString());
console.log("Expected: ", expected2.toString());
console.log("Sorted: ", customSort(input2).toString());
Sivasankar
  • 753
  • 8
  • 22
0

Updated**

it does not work with array.concat but with this merge function, don't know why....

Here is a kind of solution,

Array.prototype.merge = function(/* variable number of arrays */){
    for(var i = 0; i < arguments.length; i++){
        var array = arguments[i];
        for(var j = 0; j < array.length; j++){
            if(this.indexOf(array[j]) === -1) {
                this.push(array[j]);
            }
        }
    }
    return this;
};

var $a = [10, 7, 12, 3, 5, 6];
var $b = [12, 8, 5, 9, 6, 10];

function reorganize($array){

  var $reorganize = [];

  $reorganize.push($array.shift());

  $array.sort(function(a, b) { return a - b; });

  $reorganize.merge($array);

  return $reorganize;
}

console.log(reorganize($a));
console.log(reorganize($b));
fxlacroix
  • 557
  • 4
  • 18
  • 1
    Regarding your update: `concat` returns a new array, you were using it as if it would modify your original array. `$reorganize = $reorganize.concat($array);` should do it. – Marvin Jun 09 '17 at 12:25
0

My proposal is based on:

  • reduce original array into two containing the lower and upper numbers to the first one
  • sort each array and concatenate

In this way the initial problem is divided in two sub problems that are more simple to work on.

function cSort(arr) {
    var retval = arr.reduce(function (acc, val) {
        acc[(val < arr[0]) ? 1 : 0].push(val);
        return acc;
    }, [[], []]);
    return retval[0].sort((a, b) => a-b).concat(retval[1].sort((a, b) => a-b));
}

//
//  test
//
console.log(cSort([10, 7, 12, 3, 5, 6]));
console.log(cSort([12, 8, 5, 9, 6, 10]));
console.log(cSort([12, 8, 5, 9, 12, 6, 10]));
console.log(cSort([12]));
console.log(cSort([]));
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
0

I'm using Java:

     int[] arr = {10, 7, 12, 3, 5, 6};
     List<Integer> arr_1 = new ArrayList<Integer>();
     for(int i = 0; i < arr.length; i++)
     {
         arr_1.add(arr[i]);
     }
     Collections.sort(arr_1.subList(1,arr_1.size()));


    System.out.println(arr_1);
Kun
  • 580
  • 2
  • 13