user3500017
user3500017

Reputation: 197

Sort four numbers without an array

I have an exercise where I need to put four numbers in ascending order and then descending without using arrays. I can only use loops and if statements. I've done it with three numbers, but now with four numbers I am unable to think of the logic.

  float great1 = 0, great2 = 0, great3 = 0, great4 = 0;
  int a = 7, b = 5, c = 6, d = 0;

  // Descending
  if (a > b && b > c) {
    great1 = a;
    great2 = b;
    great3 = c;

  } else if (a > b && b < c) {
    great1 = a;
    great2 = c;
    great3 = b;

  } else if (b > a && a > c) {
    great1 = b;
    great2 = a;
    great3 = c;

  } else if (b > a && a < c) {
    great1 = b;
    great2 = c;
    great3 = a;

  } else if (c > a && a > b) {
    great1 = c;
    great2 = a;
    great3 = b;
  }

  else {
    great1 = c;
    great2 = b;
    great3 = a;
  }

Upvotes: 5

Views: 24236

Answers (2)

Boann
Boann

Reputation: 50041

A nice way to sort a small, fixed size of inputs is using a "sorting network".

This network sorts 4 elements, a b c d. Each line compares and swaps two elements:

int swap;
if (a > b) { swap = a; a = b; b = swap; }
if (c > d) { swap = c; c = d; d = swap; }
if (a > c) { swap = a; a = c; c = swap; }
if (b > d) { swap = b; b = d; d = swap; }
if (b > c) { swap = b; b = c; c = swap; }

If you want to sort in reverse order, just flip the > signs to < signs.

Links:

Upvotes: 27

nady saptra
nady saptra

Reputation: 47

I don’t know if this is correct or not. It might be better if it can be optimized.

// Sorted array
var t = [31, 32, 33, 34, 35, 36, 37, 38];
var expected = [38, 37, 36, 35, 34, 33, 32, 31];
var s = 0;
for (let i = 0; i < t.length; i++) {
  if(Math.round(t.length / 2) <= i) {
    var f = t[i];
    var g = t[t.length - i - 1];
    t[i] = g;
    t[t.length - i - 1] = f;
  }
}
if(JSON.stringify(t).replace(/ /g) == JSON.stringify(expected).replace(/ /g)) {
  console.log('true');
}
else {
  console.log('false');
}

This will swap value in between the center.

Upvotes: -4

Related Questions