Swati
Swati

Reputation: 473

Unable to sort an Arraylist

Trying to print output as:

First max

First min

Second Max

Second min

Third Max ... and so on

This is my code:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;


public class Arraylist1 {
public static void main(String args[]){
 List <Integer>list= new ArrayList <Integer> ( );
 list.add(20);
 list.add(30);
 list.add(70);
 list.add(50);
 list.add(60);
 list.add(40);
 for(int i=0;i<list.size();i++) {  
  if(i%2==0){
    Object num=Collections.max(list);
    System.out.println(num);
    list.remove(num);     
  }
 else if(i%2!=0)
    {
    Object num1=Collections.min(list);
    System.out.println(num1);
    list.remove(num1);
    }
}
}
}


 70
 20
 60

Why it printing only first three numbers?

My expected output:

 70 20 60 30 50 40

Upvotes: 1

Views: 109

Answers (3)

GhostCat
GhostCat

Reputation: 140525

Your problem is that your loop iterates until until reachig list.size().

But you keep decreasing that size on the one hand; but on the other hand, you keep re-computing that loop condition!

You have to assign that size to a helper variable like initialSize and compare against that fixed value instead!

Upvotes: 1

aathira.prabhakar
aathira.prabhakar

Reputation: 61

With Every list.remove(), the size of list gets decremented. So the loop only runs 3 times. You can use a while loop instead.

public static void main(String args[]){
    List<Integer>list= new ArrayList <Integer> ();
    list.add(20);
    list.add(30);
    list.add(70);
    list.add(50);
    list.add(60);
    list.add(40);
    int i =0;
    while(!list.isEmpty()) {  
        if(i%2==0){
            Object num=Collections.max(list);
            System.out.println(num);
            list.remove(num);
        }
        else if(i%2!=0) {
            Object num1=Collections.min(list);
            System.out.println(num1);
            list.remove(num1);
        }
        i++;
    }
}

Upvotes: 0

camickr
camickr

Reputation: 324147

for(int i=0;i<list.size();i++)

You looping condition is incorrect.

You don't loop 6 times.

You only loop 3 times because the size changes as you remove an item from the list in each iteration.

So you probably want:

int max = list.size();

for(int i = 0; i < max; i++)

That is you want to fix the loop to be the initial number of entries in the list.

Upvotes: 1

Related Questions