使用Java语言编写数据结构。要求,在一个类中编写冒泡排序和选择排序
时间: 2024-03-02 15:49:55 浏览: 24
好的,以下是使用Java语言编写冒泡排序和选择排序的示例代码:
冒泡排序:
```java
public class BubbleSort {
public static void bubbleSort(int[] arr) {
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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
}
```
选择排序:
```java
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};
selectionSort(arr);
System.out.println(Arrays.toString(arr));
}
}
```
这里我们分别在`BubbleSort`类和`SelectionSort`类中编写了冒泡排序和选择排序的静态方法`bubbleSort()`和`selectionSort()`,并且在`main()`方法中演示了这两个方法的使用。