Reputation: 191
Input array: [200, 8, 10, 60, 30, 80];
Output am getting: [200, 10, 60, 80, 30, 8];
Output required: [200, 60, 80, 8, 10, 30];
Objective: If the array element is less than 50 then move it to the bottom of the array but maintain the order of the array (by shifting left before inserting the less than 50 element to the bottom). An example is as shown above.
Problems:
1. Even though 10 is less than 50 it is still not moved to the bottom.
2. 8 should be before 30 because it will be moved first to the bottom and then 30 is moved. But 8 is at the last.
My Java code:
import java.util.*;
public class chapte1_17
{
public static void main(String[] args)
{
int list[] = new int[] {200, 8, 10, 60, 30, 80};
int length = list.length;
int value = 50;
int temp;
//System.out.println(length);
for ( int i = 0 ; i < list.length ; i++ )
{
if (list[i] < value) {
int remIndex = i;
temp = list[i];
//System.out.println(remIndex);
//System.out.println(temp);
for ( int j = remIndex ; j < list.length - 1 ; j++ )
{
list[ j ] = list[ j + 1 ] ;
}
list[list.length -1] = temp;
}
System.out.println(list[i] + "");
}
}
}
I am new to sorting and Java - any help would be appreciated.
Upvotes: 0
Views: 138
Reputation: 3557
The following might be a bit easier:
int list[] = new int[] {200, 8, 10, 60, 30, 80};
List high = new ArrayList();
List low = new ArrayList();
for (int i = 0; i < list.length; i++) {
int temp = list[i];
if (temp >= 50) {
high.add(temp);
} else {
low.add(temp);
}
}
List test = new ArrayList();
test.addAll(high);
test.addAll(low);
Object[] newList = test.toArray();
There's probably an easier way with arrays, but the is the one i could think of that was easiest =)
Upvotes: 0
Reputation: 9775
First, your output is wrong, you should loop over array when the first for loop finishes.
for (int i = 0; i < list.length; i++) {
//code
}
for (int i = 0; i < list.length; i++) {
System.out.println(list[i] + "");
}
Second thing is the logic of the moving, try something like this:
int list[] = new int[] { 200, 8, 10, 60, 30, 80 };
int length = list.length;
int value = 50;
int temp;
int actual_i = 0;
// System.out.println(length);
for (int i = 0; i < list.length; i++) {
if (list[i] < value && actual_i < list.length - 1) {
int remIndex = i;
temp = list[i];
// System.out.println(remIndex);
// System.out.println(temp);
for (int j = remIndex; j < list.length - 1; j++) {
list[j] = list[j + 1];
}
list[list.length - 1] = temp;
i--;
}
actual_i++;
}
for (int i = 0; i < list.length; i++) {
System.out.println(list[i] + "");
}
Upvotes: 1