3

I'm having trouble manually sorting the array with a for loop. It works except for the first and last number. Here's my code:

Scanner numInput = new Scanner(System.in);

int tempVar, num;
String numbersString;
int[] numbers = {4, 11, 13, 12, 17, 35, 15, 7, 19, 3, 45};

for (int i = 0; i < numbers.length - 1; i++)
{
  for(int j = 0; j < numbers.length - 1; j++)
  {
    if(numbers[i] < numbers[j + 1])
    {
      tempVar = numbers [j + 1];
      numbers [j + 1]= numbers [i];
      numbers [i] = tempVar;
    }
  }
} 

numbersString = Arrays.toString(numbers);

System.out.println(numbersString);
1
  • 1) Instead of j+1, you could use j and ` for(int j = 1; j < numbers.length; j++)` 2) The inner loop doesn't have to start with 0 or 1, it can start with i+1 Commented Jan 12, 2016 at 13:45

8 Answers 8

5

You have to initialize the value for j as i+1, this sorting algorithm is called bubble sort, that works by repeatedly swapping the adjacent elements if they are in wrong order. The below method is always runs O(n^2) time even if the array is sorted.

public static void main (String[] args)
{
    int[] array = {4,2,1,3,5,9,6,8,7};

    for(int i = 0 ; i < array.length;i++)
    {
        for(int j = i+1 ; j< array.length;j++)
        {
            if(array[i] > array[j])
            {
                int temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

2
 public int[] sort(int[] arr) {

        int marker, i, temp;
        marker =0;
        i = 1;

        while (marker < arr.length - 1) {
            if (i == arr.length) {
                marker++;
                i = marker;
            }

            if (arr[marker] > arr[i]) {
                temp = arr[marker];
                arr[marker] = arr[i];
                arr[i] = temp;
            }

            i++;
        }

        return arr;
    }

2 Comments

Hi, while this may answer the question, it is recommended to add a bit of context along with code such as to explain to how your code answers the question, what causes the issue etc. along with the code to give everyone who comes across this answer context into how and/or why this is a solution.
Hi, I don't understand English well sorry, I can't discussion with you, it's only alternative method
0

Try this one:

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

You have little wrong second for iteration and reverse condition.

1 Comment

Ah! Thank you for the input
0

you have some errors in your code. I make some modifications, please look:

int tempVar, num;
String numbersString;
int[] numbers = {4, 11, 13, 12, 17, 35, 15, 7, 19, 3, 45};

for (int i = 0; i < numbers.length; i++) {
    for (int j = i; j < numbers.length; j++) {
        if (numbers[i] < numbers[j]) {
            tempVar = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = tempVar;
        }
    }
}

numbersString = Arrays.toString(numbers);

System.out.println(numbersString);

First, I recommend you to iterate in the second loop, from i (beacause the items previous i are now sorted).

Second, you have to switch the items on i and j positions.

Finally, beacause you use < strict comparator un your loops break, you have to go user numbers.length and not numbers.length - 1 .

For more information, please see the buble sort algorithm

Comments

0

I will provide a modified version of your code with the intention of explaining why your code does not work. First, we need to decide specifically what we want to do. Lets say we want to sort the numbers in descending order.

What does this mean? Every time when we are comparing two values at lowIndex and highIndex, we want to make sure that the value at lowIndex is higher than the value at highIndex.

The problem with your code is that it does not keep track of which index, i or j+1, that is lower.

  • When i==1 and j+1==2, your code will swap the values so that the greatest value out of numbers[1] and numbers[2] will be put at index 1.
  • When i==2 and j+1==1, your code will swap the values so that the smallest value out of numbers[1] and numbers[2] will be put at index 1.

This is incosistent. The algorithm is competing with itself, trying to move values in different directions. If we modify your code to check that we are consistent in whether we want to swap large values towards the beginning of the array or towards the end, your algorithm will start to work:

    for (int i = 0; i < numbers.length - 1; i++)
    {
      for(int j = 0; j < numbers.length - 1; j++)
      {
        if(numbers[i] < numbers[j + 1] && i < (j + 1)) //NOTE: additional condition for indices
        {
          tempVar = numbers [j + 1];
          numbers [j + 1]= numbers [i];
          numbers [i] = tempVar;
        }
      }
    } 

Note, however, that the example above is just for explaining what goes wrong in execution of your code. Rather than using this code, it would probably be more appropriate to use one of the other answers to this question, or study and compare sorting algorithms on wikipedia

Comments

0

Try this

class desc
{

void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        System.out.print("  "+arr[i]);
    }
}
void sort(int arr[],int n)
{   
   for (int i = 1; i < n; i++) 
    {

        if(arr[i] < arr[i - 1] )
         {
            arr[i] = arr[i] + arr[i - 1];
            arr[i - 1] = arr[i] - arr[i - 1];
            arr[i] = arr[i] - arr[i - 1];
            i=0;

        }
    }

}


public static void main(String []args)throws Exception
{

   int[] arr = {-5, 0, -7, -2, -5, 1, -9, -1};
    int n = arr.length;
    desc d=new desc();
    d.sort(arr,n);
    d.printArray(arr, n);
  }
}

Comments

0

I believe what you are willing to do is selection sort? https://en.wikipedia.org/wiki/Selection_sort An other option I see is bubble sort but I'll try to explain selection sort.

So the first iteration of the outer for loop, the one with i, you check the whole array for the smallest number with the inner for loop, the one with j, and you put the smallest number upfront in the array. During the second iteration of the outer for loop you only go over the numbers you haven't checked yet, which is the second number through the last number. During the third iteration you go over the third number through the last number and so on. Here's how I adjusted your code, I adjusted the inner for loop so with each iteration you check a smaller sub-list and adjusted your if clause so that the smallest number is found:

    int tempVar;
    String numbersString;
    int[] numbers = {4, 11, 13, 12, 17, 35, 15, 7, 19, 3, 45};

    for (int i = 0; i < numbers.length - 1; i++)
    {
        // each iteration i you would need to go over a smaller array, so you set j = i each time
        for(int j = i; j < numbers.length - 1; j++){
            // checking if numbers[i] is greater than numbers[j + 1] instead of smaller than
            if(numbers[i] > numbers[j + 1]){
                tempVar = numbers [j + 1];
                numbers [j + 1]= numbers [i];
                numbers [i] = tempVar;
            }
        }
    } 
    numbersString = Arrays.toString(numbers);
    System.out.println(numbersString);

Comments

0
    for(int i = 0; i < nums.length - 1; ++i){
        for(int j = i + 1; j < nums.length; ++j){
            if(nums[i]>nums[j]){
                int tempVar = nums[i];
                nums[i] = nums[j];
                nums[j] = tempVar;
            }
        }
    }
    
    return nums;
}

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.