1

I have this code;

They both use system.out.println statements to print out the array elements. Originally I used a return statement with Arrays.toString(array) to show the array in the main method that worked fine. Now I could like to use print statements just to keep the level of complexity down. As you can see the output form sort is missing the last element in the array, this is because I am using array.length -1. however if I don't use array.length -1 I will get an .ArrayIndexOutOfBoundsException so anyone have a practical solution for this?

import java.util.Arrays;
public class SortMethod
{
    static int[] array = {2,1,5,3,5};


    public void sort(int[] arrays)
    {

        for(int i = 0;i < arrays.length - 1;i++ )
        {
            int store = 0;
            if (arrays[i + 1 ] < arrays[i])
            {
                store = arrays[i];
                arrays[i] = arrays[i + 1];
                arrays[i + 1] = store;

            }
            System.out.print(arrays[i]);
        }

        System.out.println();
    }

    public void reverse (int[] arrays)
    {   
        for (int i=arrays.length-1; i >=0; i--)
        {
            System.out.print(arrays[i]);
        }


    }
    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub

        SortMethod sort = new SortMethod();
        sort.sort(array);
        sort.reverse(array);

    }

}

Output;

From Sort:1235
From Reverse:55321
3
  • A "practical solution" would be to use Arrays.sort and Collections.reverse, just saying. =) Commented Sep 1, 2013 at 3:11
  • sbat@ yes that would be the most practical solution :) I'm doing it the hard way for understanding purposes :) Commented Sep 1, 2013 at 3:16
  • This isn't actually a working sort. Try it with {3, 2, 1}. Commented Sep 1, 2013 at 3:17

5 Answers 5

2

First of all your sorting method doesn't actually sort properly. You check values with the value immediately to its left, but what happens if you have a 4 at the end of the list?

{2,1,5,3,5,4}

would return the result:

123545

which is hardly sorted... You'll want to take every value you switch, and check it backwards as well making sure its not also smaller than the previous value. Right now you sort values to the right but never back to the left.

Also you can just do the sorting algorithm, and then iterate through the array afterwards and print the values then, rather than trying to print them in the middle of the sorting method:

public class TestCode
{
static int[] array = {2,1,5,3,5,4,9,1,99,7};


public void sort(int[] arrays)
{

    for(int i = 0; i < arrays.length - 1 ;i++ )
    {
        int store = 0;
        // Move larger values to the right
        if (arrays[i] > arrays[i + 1])
        {
            store = arrays[i];
            arrays[i] = arrays[i + 1];
            arrays[i + 1] = store;
            // Sort swapped smaller values to the left
            for(int j = i; j > 1; j--)
            {
                if (arrays[j] < arrays[j - 1])
                {
                    store = arrays[j];
                    arrays[j] = arrays[j - 1];
                    arrays[j - 1] = store;
                }
            }

        }
    }

    for(int i = 0; i < array.length; i ++)
    {
        System.out.print(arrays[i] + " ");
    }
    System.out.println();
}

public void reverse (int[] arrays)
{   
    for (int i=arrays.length-1; i >=0; i--)
    {
        System.out.print(arrays[i] + " ");
    }


}
/**
 * @param args
 */
    public static void main(String[] args)
    {
        // TODO Auto-generated method stub

        TestCode sort = new TestCode();
        sort.sort(array);
        sort.reverse(array);

    }

}

Gives the output:

1 1 2 3 4 5 5 7 9 99

99 9 7 5 5 4 3 2 1 1

SUMMARY:

When sorting arrays you'll need to iterate though the array array.length - 1 times to compare the values (you don't need to compare the last value with the value to its right because there isn't one).

When printing an array you need to iterate through it array.length times and print out each and every value. Your main problem is coming from trying to print out the array in your sorting algorithm which is only iterating through the array array.length - 1 times when you should probably just print the array outside of the sorting algorithm.

Sign up to request clarification or add additional context in comments.

1 Comment

The confusion for the Ops seems to come from iterating for sorting in a bubble-sort style method and, in the same loop, printing values. A sort typically needs to iterate 1 less than the length of the list/array while printing the list needs to iterate every entry.
1

The last line of the public void sort(int[] arrays) function:

   System.out.println();

should be

System.out.println(arrays[arrays.length - 1]);

as you want to print the hole array.

And for the record, the public void sort(int[] arrays) function does not actually sort an array. It is not what the sort should do just by one pass of checking and swapping of the neighboring elements.

For example, if the array is initialized as:

static int[] array = {2,1,5,3,5};

The resulting array of sort is: 53215, and the reversed array is 51235. Both are not the intended result.

Comments

1

In sort() you're iterating from 0 to arrays.length-1 (exclusive), so for arrays.length==5 variable i will take values: 0, 1, 2, 3

In reverse() you iterate from arrays.length-1 (inclusive) to 0 - i will take values: 4, 3, 2, 1, 0.

When you remove -1 part from arrays.length-1 in sort() you're getting ArrayOutOfBoundsException because you reference arrays[i + 1] which will be out of arrays range for i==4.

Comments

1

Change your sort method as follows :

public void sort(int[] arrays) {
        // int i = 0;
        for (int i = 0; i < arrays.length - 1; i++) {
            int store = 0;
            if (arrays[i + 1] < arrays[i]) {
                store = arrays[i];
                arrays[i] = arrays[i + 1];
                arrays[i + 1] = store;

            }
            System.out.print(arrays[i]);
            if (i + 1 == arrays.length - 1) {
                System.out.print(arrays[i + 1]);
            }
        }

        System.out.println();
    }

Just added a new print statement

if (i + 1 == arrays.length - 1) {
System.out.print(arrays[i + 1]);
}  

to print the last array element.

2 Comments

This does not sort arrays either.
Question was about the missing last element and this exactly answers that.As you can see, this is the same code that was posted as part of the original question,I have just added a print statement to print the last array element. And yes, this is obviously a broken sort algorithm.
1

First of all I would like to point out that the code is incomplete. This is just half the sorting code, I can see you are trying to use bubble sort, but unfortunately the inner loop is missing.

Apart from this there is no problem in this code.

Could you just replace your sort method with the one given below? This will fix all the issues.

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

      }

    }
    printArray(a);
  System.out.println();
}


public void printArray(int[] a){
    for(int i = 0 ; i < a.length ; i++){
        System.out.print(a[i]);
    }
}

Also, I would recommend you to read about sorting techniques. You can always visit Sorting articles

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.