【发布时间】:2015-12-16 22:28:16
【问题描述】:
我的目标是根据事件的日期对包含事件的矩阵进行排序(作为 events[eventIndex][1] 存储在矩阵中。不知何故,我得到了几乎正确的输出,除了以 bold显示的部分>
我必须分别对年、月和日进行排序吗? 还是我的比较方法中有一些逻辑错误?
排序前:
2015 年 12 月 24 日
2015 年 12 月 19 日
2015 年 12 月 30 日
2015 年 11 月 13 日
2015 年 12 月 30 日
2016 年 1 月 15 日
2015 年 12 月 31 日
2016 年 1 月 15 日
2015 年 12 月 24 日
2015 年 12 月 19 日
2015 年 12 月 31 日
2016 年 1 月 15 日
排序后:
2015 年 11 月 13 日
2015 年 12 月 19 日
2015 年 12 月 19 日
2015 年 12 月 24 日
2015 年 12 月 24 日
2015 年 12 月 30 日
2015 年 12 月 31 日
2015 年 12 月 30 日
2015 年 12 月 31 日
2016 年 1 月 15 日
2016 年 1 月 15 日
2016 年 1 月 15 日
这是我的代码。
public void quickSort(String[][] event, int low, int high, Compare c) {
if (event == null || event.length == 0)
return;
if (low >= high)
return;
// pick the pivot
int middle = low + (high - low) / 2;
// make left < pivot and right > pivot
int i = low, j = high;
while (i <= j) {
while (c.compare(i, middle)) {
i++;
}
while (c.compare(middle, j)) {
j--;
}
if (i <= j) {
String[] temp = event[i];
event[i] = event[j];
event[j] = temp;
i++;
j--;
}
}
// recursively sort two sub parts
if (low < j)
quickSort(event, low, j,c);
if (high > i)
quickSort(event, i, high,c);
}
//Interface for comparing two types
public interface Compare {
boolean compare(int first, int second);
}
public class CompareDate implements Compare {
@Override
public boolean compare(int first, int second) {
//Splitting up the date string and converts into int
//Splitting first index
String[] temp = event[first][1].split("/");
int firstYear = Integer.parseInt(temp[2]);
int firstMonth = Integer.parseInt(temp[0]);
int firstDay = Integer.parseInt(temp[1]);
//Splitting second index
temp = event[second][1].split("/");
int secondYear = Integer.parseInt(temp[2]);
int secondMonth = Integer.parseInt(temp[0]);
int secondDay = Integer.parseInt(temp[1]);
//Comparing the values
if (firstYear < secondYear) return true;
else if (secondYear < firstYear) return false;
else if (firstMonth < secondMonth) return true;
else if (secondMonth < firstMonth) return false;
return (firstDay < secondDay);
}
}
【问题讨论】:
-
您可以先排序年份,然后是月份,然后是日子。甚至使用日期对象、列表和比较器
标签: java sorting date compare quicksort