gpt4 book ai didi

java - 时髦的冒泡排序 (Java Eclipse)

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

我目前正在研究一个基本的冒泡排序,除了它使用 Comparable 之外,并且让我失望,因为我不确定在哪里实现它的功能。

这是我被赋予的,无法改变

public static <T extends Comparable<? super T>> void bubbleSort_Itr(T[] arr)
{
if(arr == null) throw new NullPointerException();
if(arr.length == 0) throw new IllegalArgumentException();
if(arr.length == 1) return;
}

这是我在测试类中创建的

public class HubbaBubbaSort {

public static <T extends Comparable<? super T>> void bubbleSort_Itr(T[] arr)
{
if(arr == null) throw new NullPointerException();
if(arr.length == 0) throw new IllegalArgumentException();
if(arr.length == 1) return;

int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap T temp and arr[i]
T temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
/* Prints the array */
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}

// Driver method to test above
public static void main(String args[])
{
HubbaBubbaSort ob = new HubbaBubbaSort();
int arr[] = {64, 34, 25, 12, 22, 11, 90};
ob.bubbleSort_Itr(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}

}

最佳答案

这里的关键是Comparable接口(interface):

https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html

int compareTo(T o)

Parameters:
o - the object to be compared.

Returns:
a negative integer, zero, or a positive integer as this object is less than,
equal to, or greater than the specified object.

一旦我们知道如何比较对象,我们就可以使用它来执行冒泡排序。另外,由于 int 是一个基元,无法实现 Comparable,所以我将其切换为 Integers。

public class HubbaBubbaSort {

public static <T extends Comparable<? super T>> void bubbleSort_Itr(T[] arr) {
if (arr == null)
throw new NullPointerException();
if (arr.length == 0)
throw new IllegalArgumentException();
if (arr.length == 1)
return;

int n = arr.length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)

if (arr[j].compareTo(arr[j + 1])>0) {
// swap T temp and arr[i]
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}

/* Prints the array */
void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}

// Driver method to test above
public static void main(String args[]) {
HubbaBubbaSort ob = new HubbaBubbaSort();
Integer arr[] = { 64, 34, 25, 12, 22, 11, 90 };
ob.bubbleSort_Itr(arr);
System.out.println("Sorted array");
System.out.println(Arrays.toString(arr));
}
}

关于java - 时髦的冒泡排序 (Java Eclipse),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52673120/

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