Java 词典快速排序
我尝试使用java中的快速排序算法按字典顺序对Java 词典快速排序,java,algorithm,sorting,quicksort,Java,Algorithm,Sorting,Quicksort,我尝试使用java中的快速排序算法按字典顺序对字符串数组进行排序。使用扫描仪通过终端读入阵列,并保存在阵列列表中。这个ArrayList稍后被转换为一个数组,我(尝试)在其中应用快速排序算法。 我有两种方法: private static void sortA(String[] s, int start, int end) { if (end > start) { int pivot = partition(s, start, end); sortA
字符串数组进行排序。使用扫描仪
通过终端读入阵列,并保存在阵列列表
中。这个ArrayList
稍后被转换为一个数组,我(尝试)在其中应用快速排序算法。
我有两种方法:
private static void sortA(String[] s, int start, int end) {
if (end > start) {
int pivot = partition(s, start, end);
sortA(s, start, pivot - 1);
sortA(s, pivot + 1, end);
}
}
private static int partition(String[] s, int start, int end) {
String pivot = s[end];
int left = start;
int right = end;
String temp = "";
do {
while ((s[left].compareTo(pivot) <= 0) && (left < end))
left++;
while ((s[right].compareTo(pivot) > 0) && (right > start))
right--;
if (left < right) {
temp = s[left];
s[left] = s[end];
s[right] = temp;
printRow(s);
}
} while (left < right);
temp = s[left];
s[left] = s[end];
s[end] = temp;
return left;
}
私有静态无效排序(字符串[]s,int start,int end){
如果(结束>开始){
int pivot=分区(s、开始、结束);
排序(s,开始,枢轴-1);
排序(s,枢轴+1,结束);
}
}
私有静态整型分区(字符串[]s,整型开始,整型结束){
字符串轴=s[结束];
int左=开始;
int右=结束;
字符串temp=“”;
做{
while((s[左]。比较(pivot)0)和&(右>开始))
对--;
if(左<右){
温度=s[左];
s[左]=s[结束];
s[右]=温度;
printRow(s);
}
}而(左<右);
温度=s[左];
s[左]=s[结束];
s[结束]=温度;
左转;
}
代码似乎随机工作正常,然后突然不正常。例如,数组{“java”、“application”、“system”}
排序精细到{“application”、“java”、“system”}
。数组{“library”、“content”、“bin”}
排序为{“bin”、“library”、“contents”}
,这不是字典顺序。当然,计算机不是随机工作的,所以我的代码肯定有问题。我试着在纸上写出一个例子,但我会发现完全错了。然而,我的代码基于对双数组进行排序的快速排序实现,因此我认为我没有犯大的推理错误。
提前感谢。您以错误的方式拆分阵列:
正确的拆分为“pivot-1”“pivot”
非常感谢。看起来它现在起作用了。我犯了这么愚蠢的错误。。。我尽快接受答案!
sortA(s, start, pivot-1);
sortA(s, pivot, end);