开发者

sorting an arraylist of objects using insertion sort

开发者 https://www.devze.com 2023-02-17 18:31 出处:网络
here\'s my code that uses selection. i need to use a insertion and do not use temporary arrays or arraylist. i need help of how to do a insertion sort.

here's my code that uses selection. i need to use a insertion and do not use temporary arrays or arraylist. i need help of how to do a insertion sort.

public static void sortStudents(ArrayList<Student> list)
 {//selection sort
  Student t开发者_运维知识库empStudent;
  int count1;
  int count2;
  int largest;

  for (count1=0; count1<list.size()-1; count1++)
  {
   largest = 0;
   for (count2=largest+1; count2<list.size()-count1; count2++)
   {
    if ((list.get(largest)).compareTo(list.get(count2)) < 0)
    {
     largest = count2;
    }
   }
   tempStudent = list.get(list.size()-1-count1);
   list.set(list.size()-1-count1, list.get(largest));
   list.set(largest, tempStudent);
  }
 }
}


Both selection sort and insertion sort work quite similarly, by having a "not yet sorted" part of the list, and an "already sorted" part. In the beginning, the first one is the whole list, and the second part an empty list at the start or end. While sorting the "not yet sorted" part shrinks, while the "already sorted" part grows, by one element per iteration.

The difference between selection sort and insertion sort is this:

  • For selection sort, you search the minimum (or maximum) element of the "not yet sorted" part, remove it there and then add it to the end (or beginning) of the already sorted part.
  • For insertion sort, you take the next element of the "not yet sorted" part of the list, find it's insertion point in the "already sorted" part and insert it there.

This should be enough to change your selection sort to insertion sort.


You don't define variables outside the loop if it is only used in the loop. Restricting the lifetime of your variables makes it more easy to reason about the code.

public static void sortStudents (ArrayList<Student> list)
{
  int largest;

  for (int i=0; i < list.size () - 1; i++)
  {
    largest = 0;
    for (int j=largest + 1; j < list.size () - i; j++)
    {
      if ((list.get (largest)).compareTo (list.get (j)) < 0)
      {
         largest = j;
      }
    }
    Student tempStudent = list.get (list.size () - 1 - i);
    list.set (list.size () - 1 - i, list.get (largest));
    list.set (largest, tempStudent);
  }
}

A bit more indentation makes your code more readable. Now what's your concrete error - doesn't it compile, throws it an exception or does it produce the wrong result?

Here is something suspicious in the inner loop:

    largest = 0;
    for (int j=largest + 1; j < list.size () - i; j++)

If you set largest to 0, then j will be initialized to 0 + 1 => 1. I guess you had another intention. Did you mean j = i + 1;?

0

精彩评论

暂无评论...
验证码 换一张
取 消