44
viadukt
7y

It was a basic java lesson. We had four values that we stored in a array. We had to make some calculations with the values. Then we had to sort those four values. That's the solution our teacher proposed:
if (arr[0] > arr[1]) {
int temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
}
if (arr[1] > arr[2]) {
int temp = arr[1];
arr[1] = arr[2];
arr[2] = temp;
}
if (arr[2] > arr[3]) {
int temp = arr[2];
arr[2] = arr[3];
arr[3] = temp;
}
if (arr[0] > arr[1]) {
int temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
}
if (arr[1] > arr[2]) {
int temp = arr[1];
arr[1] = arr[2];
arr[2] = temp;
}
if (arr[0] > arr[1]) {
int temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
}

Comments
  • 12
    Its not stupid that much i suppose that your class didnt come to sorting alg yet soo this is the way to show you how that may work ( that is bubble sort but only for 4 values)
  • 4
    Hmm...
    I could see why it would be confusing to use a loop at first, because once the loop completes once it'll have sorted a couple of the numbers, they'll probably be confused why the whole thing isn't sorted. Although I don't know why they'd be teaching sorting already if they couldn't use loops properly...

    Int temp;
    For (int x =0; x<arr.size-1;x++){
    //was it .size or .length? I forget...
    If (arr[x] > arr[x+1]){
    temp = arr[x];
    arr[x] = arr[x+1];
    arr[x+1] = temp;
    x = 0; //this would be easy to forget
    }
    }

    I think this would work? Trying to practice a bit for my written midterm this week xD
  • 2
    I wouldn't ever do that .
    Besides thats just useless coding .
    Arrays ( especially ArrayList's) are the greatest things when it comes to working with many objects .
    When you get to work you will see that the most codes that teachers teach are useless
    Take this as an example .
    When we are working with arrays it means we want to hold many objects now imagine we have 999 indexs 😂
    You sure need to to loop it .
    My solution will be something like
    int count = 0;
    String first = 0;
    for(String s:stringArray){
    if(count == 0){
    // Next time go to else if
    count += 1;
    first = s;
    } else if(count == 1){
    // Second index loop
    // Reset it
    count = 0;
    // Compare first and second now
    // Theres a compare to method i dont remember
    // Or use toCharArray() and compare all chars here
    // And theres a specific method for sorting algorithm
    }
    }
  • 7
    Why not use Array.sort(arr) ? I think it's quite straightforward, more efficient and since is a basic course the aim should not be teaching algorithms
  • 0
    @Nikan my mistake there
    String first = "";
    😄
  • 0
    @agentwolf44
    arr.length*
    x= -1;*
  • 0
    Point of my comment is not to talk about my solution...
    I am just saying that thats not worst solution..
Add Comment