gpt4 book ai didi

java - java中快速排序的swap方法

转载 作者:行者123 更新时间:2023-11-30 08:37:54 26 4
gpt4 key购买 nike

谁能帮我弄清楚这个交换方法是一个更大的快速排序程序的一部分?它应该接受一个数组和两个整数,并交换整数指示的索引位置。

private static <T extends Comparable<T>> int partition(T[] table, int first, int last) {
T pivot = table[first];
int up = first;
int down = last;

do {
while ((up < last) && (pivot.compareTo(table[up]) >= 0)) {
up++;
}
while (pivot.compareTo(table[down]) < 0) {
down--;
}
if (up < down) {
swap(table, up, down);
}
}

while (up < down);
swap(table, first, down);
return down;
}

交换方法目前未定义,我不确定如何让它工作。我试过写这个方法:

void swap(T[] array, int a, int b) {
T temp = array[a];
array[a] = array[b];
array[b] = temp;
}

但是我不断收到 T 无法解析为类型的错误。但是当我尝试将类型更改为 int 时,该方法在上面调用的地方不起作用。

最佳答案

您需要添加通用类型 <T>给你的swap方法。有点像

static <T> void swap(T[] array, int a, int b) {
T temp = array[a];
array[a] = array[b];
array[b] = temp;
}

关于java - java中快速排序的swap方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36869741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com