0

I want my program to "sort" an array into two different arrays. Meaning every value that is greater than or equal to 500 goes to the array values2. Every value that is less than 500 goes to the array values3.

My problem is that whatever I try its always the last value that matches the condition that is shown.

 for (int i = 0; i < values.length && i < noOfNumbers; i++)
 {
 if (values[i] >= 500)
 {
 for (int k = 0; k < numbersAbove500; k++)
 {
 values3[k] = values[i];
 }
 }
 else 
 {
 for (int j = 0; j < numbersAbove500; j++)
 {
 values2[j] = values[i];
 }
 }
 }

Typical Output

How many numbers do you wish the array to contain? 8

These are the random numbers

877 338 741 119 20 853 235 786

These are the numbers above or equal to 500 :

786 786 786 786

These are the numbers below 500 :

235 235 235 235

asked Apr 11, 2015 at 18:14
4
  • is numbersAbove500 your counter of numbers that are larger than 500? Commented Apr 11, 2015 at 18:18
  • Why to think hard? Why not to sort just one array, and then split it to two different arrays? ;) Commented Apr 11, 2015 at 18:18
  • yeah luk2302 i use it to see the total numbers above 500 Commented Apr 11, 2015 at 18:30
  • Alex, I'm not allowed to use the sort function in this assignment. :) Commented Apr 11, 2015 at 18:31

1 Answer 1

3

You only need a single loop. Your inner loops make no sense.

int j = 0;
int k = 0;
for (int i = 0; i < values.length && i < noOfNumbers; i++) {
 if (values[i] >= 500) {
 values3[k] = values[i];
 k++;
 } else {
 values2[j] = values[i];
 j++;
 }
}
answered Apr 11, 2015 at 18:17
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.