2

I have an exercise where I need to put 4 numbers in ascending order and then descending without using arrays. I can only use loops and if statements. I've done it with 3 numbers, but now with 4 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;
  }
user3500017
  • 157
  • 2
  • 3
  • 10

2 Answers2

21

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

This network sorts 4 elements:

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

Each line does a comparison and swap between two elements.

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

Links:

Boann
  • 47,128
  • 13
  • 114
  • 141
-2

I dont know if this is correct or not. Might be better if it can be optimize

    // 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.

nady saptra
  • 41
  • 1
  • 6
  • 1
    The question specifically says "without using arrays". Also, it asks for a Java solution, and JavaScript := Java. – Dada Nov 03 '21 at 07:09
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/30244364) – Manfre Nov 03 '21 at 08:27