Java 这个BubbleSort方法可以进一步最小化吗?
我正在尝试编写一个bubblesort方法,该方法需要能够按需按降序和升序排序,同时使用最少的重复代码 到目前为止,这是我的暂时解决方案:Java 这个BubbleSort方法可以进一步最小化吗?,java,sorting,data-structures,Java,Sorting,Data Structures,我正在尝试编写一个bubblesort方法,该方法需要能够按需按降序和升序排序,同时使用最少的重复代码 到目前为止,这是我的暂时解决方案: public void burbuja() { String TipoOrdenamiento = "Max"; int i, j, aux; for (i = 1; i < A.length; i++) { for (j = A.length - 1; j >= i; j--) {
public void burbuja() {
String TipoOrdenamiento = "Max";
int i, j, aux;
for (i = 1; i < A.length; i++) {
for (j = A.length - 1; j >= i; j--) {
if (TipoOrdenamiento == "Min") {
if (A[j - 1] > A[j]) {
aux = A[j - 1];
A[j - 1] = A[j];
A[j] = aux;
}
}
if (TipoOrdenamiento == "Max") {
if (A[j - 1] < A[j]) {
aux = A[j - 1];
A[j - 1] = A[j];
A[j] = aux;
}
}
}
}
}
正如你们可能注意到的,升序排序和降序排序之间的实际差别非常小,所以我非常好奇是否有任何巧妙的技巧可以让我进一步压缩我的方法
提前感谢您的回答。使用布尔值表示j和j-1之间的比较是真是假
public static void bubbleSort(int[] A, String TipoOrdenamiento) {
boolean increasingOrder = TipoOrdenamiento == "Min";
for (int i = 1; i < A.length; i++) {
for (int j = A.length - 1; j >= i; j--) {
if (A[j - 1] < A[j] != increasingOrder && A[j - 1] != A[j]) {
int aux = A[j - 1];
A[j - 1] = A[j];
A[j] = aux;
}
}
}
}
由于您使用的是Java,这是实现通用性的好方法:
class MinComp implements Comparator<Integer>
{
public int compare(Integer a, Integer b)
{
if (a < b)
return -1;
if (a == b)
return 0;
if (a > b)
return -1;
}
}
public class Bubble
{
public static void main(String[] args)
{
MinComp minComp = new MinComp();
burbuja(minComp);
}
static public void burbuja(Comparator comp)
{
int i, j, aux;
for (i = 1; i < A.length; i++)
{
for (j = A.length - 1; j >= i; j--)
{
if (comp.compare(A[j - 1], A[j]) > 0)
{
aux = A[j - 1];
A[j - 1] = A[j];
A[j] = aux;
}
}
}
}
}
通过定义不同类型的比较器,您可以选择不同的排序。这将导致它交换相等的项,这会产生更多的工作,并且违反正常的bubblesort的稳定性保证。通过添加&&A[j-1]进行修复!=A[j]返回b-A;这是一种坏习惯。如果b-a导致整数溢出,那么它将返回错误的结果。例如,如果b==int.MAX_值,并且a像-2一样是负数,那么结果将是负数,表示b