accounting-dashboard/src/main/java/org/gcube/portlets/user/accountingdashboard/server/util/CocktailSort.java

72 lines
1.8 KiB
Java

package org.gcube.portlets.user.accountingdashboard.server.util;
import java.util.List;
import org.gcube.accounting.accounting.summary.access.model.ScopeDescriptor;
public class CocktailSort {
public enum Order {
ASC, DESC
}
public static void sort(List<ScopeDescriptor> list, Order order) {
if (list != null && list.size() > 1) {
// `begin` ed `end` first and last index to check
int begin = -1;
int end = list.size() - 1;
boolean swapped;
do {
swapped = false;
// increases `begin` because the elements before `begin` are
// sorted correctly
begin = begin + 1;
for (int i = begin; i < end; i++) {
if (order == Order.ASC) {
if (list.get(i).getName().compareTo(list.get(i + 1).getName()) < 0) {
ScopeDescriptor sd = list.get(i);
list.set(i, list.get(i + 1));
list.set(i + 1, sd);
swapped = true;
}
} else {
if (list.get(i).getName().compareTo(list.get(i + 1).getName()) > 0) {
ScopeDescriptor sd = list.get(i);
list.set(i, list.get(i + 1));
list.set(i + 1, sd);
swapped = true;
}
}
}
if (swapped == false) {
break;
}
swapped = false;
// decreases `end` because the elements after `end` are sorted
// correctly
end = end - 1;
for (int i = end; i > begin; i--) {
if (order == Order.ASC) {
if (list.get(i).getName().compareTo(list.get(i - 1).getName()) > 0) {
ScopeDescriptor sd = list.get(i);
list.set(i, list.get(i - 1));
list.set(i - 1, sd);
swapped = true;
}
} else {
if (list.get(i).getName().compareTo(list.get(i - 1).getName()) < 0) {
ScopeDescriptor sd = list.get(i);
list.set(i, list.get(i - 1));
list.set(i - 1, sd);
swapped = true;
}
}
}
} while (swapped);
}
}
}