Can someone explain this java sort method (or link me an explanation)?

I didn’t quite understand how the looping works. This is meant to be a method that sorts the array in ascending order.

public void sort(){
    int maxCompare = a.length - 1;
    int lIndex = 0;
    int temp = 0;
    for (int i = maxCompare; i > 0; i--){
        lIndex = i;
        for (int j = i - 1; j >= 0; j--){
            if (a[j] > a[lIndex]){
                lIndex = j;
        temp = a[i};
        a[i] = a[lIndex];
        a[lIndex] = temp;

With what exactly do you have troubles? Have you tried to go through it step-by-step with some example?

I think it was from the for loop to the end of the code. I couldn’t really find examples online.

I’ll see if I can help. This is a very basic sort algorith designed to sort an array called a. It’s going to do it with two loops. What it will do is start at the last item in the array. It will go through all items looking for the largest value, and after it has found the largest will stick it on the end. Then it will move to the next to the last item, and search again. It keeps doing that until its gone through and ordered it from back to front.

So, to start

public void sort(){
    int maxCompare = a.length - 1;    //<---This points to end of the array
    int lIndex = 0;    //<---this will be used store the location of the largest found value
    int temp = 0;    //<---this will be used to move values around.
    for (int i = maxCompare; i > 0; i--){   //<--- start at the last item in the array - i is where you're at in the process
        lIndex = i;   //<--- to start, set IIndex to where youre starting

        for (int j = i - 1; j >= 0; j--){        //<--- start at i, go through all items from the end of the array to the front 
            if (a[j] > a[lIndex]){      //<--- if you find a bigger value, set the iindex to that location
                lIndex = j;

        // At this point, its searched every value and iindex is the location of the biggest number

        temp = a[i};           //<------ these lines swap the largest value at iindex with the 
        a[i] = a[lIndex];            // last item in the array (where your i points to)
        a[lIndex] = temp;

     // You've now put the largest value at the end of your array, so
   // the 'i' loop continues, decrementing by one, and now tries to find the 
   // next biggest value to put at the second to last spot in the array, and keeps 
   // doing that until all items are put in order. 

Hope that helps.

That helps! You have my thanks :]

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.