JasonAmp
JasonAmp

Reputation: 11

I am working on a basic sorting algorithm for an array, that I don't quite fully understand, even though the solution works

I am a little unclear around the if-statement block of code section, during the loop. I am not quite clear on the thought process behind setting the first and next element to to different variables and setting those true and false variables, feedback would be appreciated, thanks.

here is my code:

public void SortArray()
{
    Boolean isSorted = true;
    while(isSorted)
    {
        isSorted = false;
        for(int i=0;i<ArrayOfValues.length;i++)
        {
            for(int j=i+1;j<ArrayOfValues.length;j++) 
            {
                if(ArrayOfValues[i]>ArrayOfValues[j])
                {
                    int temp = ArrayOfValues[j];
                    ArrayOfValues[j] = ArrayOfValues[i];
                    ArrayOfValues[i] = temp;
                    isSorted = true;
                }
            }


        }
    }
}

Upvotes: 0

Views: 55

Answers (1)

Moussaabmma
Moussaabmma

Reputation: 78

if you mean this code

int temp = ArrayOfValues[j];
                    ArrayOfValues[j] = ArrayOfValues[i];
                    ArrayOfValues[i] = temp;

then it is only for swaping when the the current element is bigger than the nest element, the algorithm swap it this way. an easy explanation of how the swap works is try to imagin two cups, one is filled with water the second is filled with coffee and you want the swap them. you would bring an empty cup (represent the temp variable in the code). you fill the empty cup with water, now the cup that had water before is empty and you fill it with coffe. now the cup that has once water is filled with coffee , and the coffe cup is empty, you fill the coffee cup with the water you put first in the new cup. i hope this explain it

Upvotes: 2

Related Questions