I'm trying to sort a set of objects based on 1 v 1 choice. To do so, I'm basically assuming that if A>B and B>C, then A>C. This will reduce the number of questions significantly.
When you are adding a new element to the sorted list you need to see if it belongs to the upper or lower part of the list so you compared to the middle element. You continue doing it until you find the exact position.
This code doesn't do that quite well, obviously the error is on the while loop, but I can't seem to find it. Sometimes when it should be placed last sometimes it doesn't, others it display the question more than once ...
For reference this algorithm is very similar to mine (Sorting a set of objects by a user's preference)
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
static String [] list = {"mac n cheese", "kebab", "burger", "pizza"};
private static int compare(String s1, String s2) {
Scanner sc=new Scanner(System.in);
System.out.println("Which one do you prefer? "+s1+" or "+s2+". Press 0 if the first or 1 if the second");
return sc.nextInt();
}
public static void main(String[] args) {
ArrayList<String> sort = new ArrayList();
/*pseudo
Add first two elements by comparison
Select one element and see where it belongs
do until last one is placed
*/
double pos;
int n=compare(list[0], list[1]);
if(n==1){
sort.add(list[1]);
sort.add(list[0]);
}
else {
sort.add(list[0]);
sort.add(list[1]);
}
double s=0.0;
for(int i=2; i<list.length; i++) {
s=(double) sort.size()/2;
pos=s;
n=(int) pos;
do {
if(sort.size()<=n) {
break;
}
if(n<0) {
n=0;
break;
}
n=compare(list[i], sort.get(n));
s=s/2;
if(n==0) {
pos=pos-s;
}
else {
pos=pos+s;
}
n=(int) pos;
if((pos-(double)n)>=0.5) {
n++;
}
}while(s>0.5);
sort.add(n, list[i]);
}
for(int i=0; i<list.length; i++) {
System.out.println((i+1)+". "+sort.get(i));
}
}
}