我怎樣才能排序這個列表(降序)?它增加了數字,但按升序排序,但我希望它下降(不使用任何外部庫或任何東西)。我試圖弄清楚,但沒有拿出任何東西。排序一個列表(降序)
private void addNewElement()
{
//getting the input
System.out.print("Please type the number to be added to the list: ");
Integer newValue = null;
while(newValue == null)
{
try
{
newValue = Integer.parseInt(userInput.nextLine());
}
catch (final Exception e)
{
System.out.println("Wrong value. Please insert new value.");
}
}
//creating new element based on the input
MyListElement newElement = new MyListElement(newValue);
//if not first
if (firstElement != null)
{
placeElementInList(newElement);
}
else
{
firstElement = newElement; //if first
}
}
//if not first
private void placeElementInList(final MyListElement newElement)
{
//if smaller than first
if (newElement.value < firstElement.value)
{
newElement.nextElement = firstElement; //new points to first
firstElement = newElement; //and becomes first
}
else
{
MyListElement previousElement = firstElement; //have to remember previous element
MyListElement elementInList = firstElement.nextElement; //currently checked.
while (elementInList != null)
{
if (newElement.value < elementInList.value) //if new element is smaller that currently checked
{
break; //break - put it in current position.
}
previousElement = elementInList; //if not, move forward, substitute variables
elementInList = elementInList.nextElement;
}
previousElement.nextElement = newElement; //set the new element at the proper position
newElement.nextElement = elementInList; //
}
}
使用'Collections.sort'和'Comparator'。 – Mena 2014-09-05 18:22:56
降序與升序相同,除非您翻轉標誌。您應該可以通過更改一行代碼來更改另一個。 – 2014-09-05 18:24:40
'if(newElement.value> elementInList.value)'... – R2B2 2014-09-05 18:25:28