我正在尝试在 Java 中实现快速排序算法:
// Sort parallel arrays with quick sort
import java.util.Scanner;
import java.text.DecimalFormat;
class FunRunQuiSort {
static int iSize = 5; // Set value
static double[] daFinishTime = new double[iSize];
static String[] saRunnerName = new String[iSize];
static void getInput() {
System.out.println("\n***** 5K RUNNERS *****");
for(int i = 0; i < saRunnerName.length; i++) {
Scanner input = new Scanner(System.in);
System.out.print("Enter runner name: ");
saRunnerName[i] = input.nextLine();
System.out.print("Enter finish time: ");
daFinishTime[i] = input.nextDouble();
System.out.print("\r\n");
}
}
static void doQuickSort(double[] daFinishTime) {
int i = daFinishTime[0], j = daFinishTime.length - 1;
double dTemp;
String sTemp;
// Pivot
double dPivot = daFinishTime[(daFinishTime[0] + daFinishTime.length - 1) / 2];
// Partition
do {
while(daFinishTime[i] < dPivot) {
i++;
}
while(daFinishTime[j] > dPivot) {
j--;
}
if(i <= j) {
dTemp = daFinishTime[i];
daFinishTime[i] = daFinishTime[j];
daFinishTime[j] = dTemp;
sTemp = saRunnerName[i];
saRunnerName[i] = saRunnerName[j];
saRunnerName[j] = sTemp;
i++;
j--;
}
} while(i <= j);
// Recursion
if(daFinishTime[0] < j) {
doQuickSort(daFinishTime, daFinishTime[0], j);
}
if(i < daFinishTime.length - 1) {
doQuickSort(daFinishTime, i, daFinishTime.length - 1);
}
}
static void printOutput() {
DecimalFormat df = new DecimalFormat("##.00");
System.out.println("***** SORTED RUNTIMES *****");
for(int i = 0; i < daFinishTime.length; i++) {
System.out.println("[" + (i + 1) + "] " +
df.format(daFinishTime[i]) + " mins. by " +
saRunnerName[i]);
}
System.out.println("\n***** TOP 3 RUNTIMES *****");
for(int i = 0; i < 3; i++) {
System.out.println("#" + (i + 1) + " Place: " +
df.format(daFinishTime[i]) + " mins. by " +
saRunnerName[i]);
}
}
public static void main(String[] args) {
getInput();
doQuickSort(daFinishTime);
printOutput();
}
}
它正在返回精度错误,但是当我更改所述行的数据类型时,它会返回更多的精度错误。
有人可以修复代码吗?我只需要看看快速排序的实际效果。