Hi I have been working on a solution for days, and I’ve been trying to figure it out on my own but I just can’t.
I have an ArrayList and I want to swap the elements in it. But I want to compare the list in halves. So say if the list had 8 elements in it, I would want to compare the first element in the first half of the list with the first element in the second half of the list.
So list[0] with list[4] and if 4 is bigger than 0, i want to swap them, then i want to increment 0 and by 1, and half the list by one, until i = 4.
I have to run it from the command line.
import java.util.Arrays;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Collections;
public class TennisTournament {
public static void main (String [] args) {
Scanner input = new Scanner(System.in);
ArrayList <Integer> nums = new ArrayList<Integer>();
while (input.hasNextInt()) {
nums.add(input.nextInt());
}
tournament(nums); }
public static void tournament(ArrayList <Integer> list) {
int midPoint = list.size()/2; // returns the index number of half of the lists size
for (int i = 0; i < midPoint; i++) { // while is bigger than mid point, increment by one
if (list.get(i) < list.get(midPoint)) {
Collections.swap(list, i, midPoint);
System.out.print(list);
}
}
System.out.println(list); }
}
This is what I have so far, but when I run it from the command line, it just returns an ordinary list, and I’m completely stumped. I would much rather use a loop than the collections method as it is not a style of programming i am particular familiar with.
Look at
midPoint– it never changes inside the loop. You’re continually exchanging the i-th element (provided that the “if” condition is true) with themidPoint. No element aftermidPointis ever touched.