请用Java写出冒泡和快速排序实现排序程序,要求从键盘输入10个整数,输出排序结果16分]
时间: 2023-07-04 11:12:41 浏览: 223
用Java写出冒泡排序的算法
冒泡排序实现:
```java
import java.util.Scanner;
public class BubbleSort {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] arr = new int[10];
System.out.println("请输入10个整数:");
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
}
input.close();
// 冒泡排序
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// 输出排序结果
System.out.println("排序结果为:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
快速排序实现:
```java
import java.util.Scanner;
public class QuickSort {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] arr = new int[10];
System.out.println("请输入10个整数:");
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
}
input.close();
quickSort(arr, 0, arr.length - 1);
// 输出排序结果
System.out.println("排序结果为:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void quickSort(int[] arr, int left, int right) {
if (left < right) {
int pivot = partition(arr, left, right);
quickSort(arr, left, pivot - 1);
quickSort(arr, pivot + 1, right);
}
}
public static int partition(int[] arr, int left, int right) {
int pivot = arr[left];
int i = left, j = right;
while (i < j) {
while (i < j && arr[j] >= pivot) {
j--;
}
if (i < j) {
arr[i++] = arr[j];
}
while (i < j && arr[i] <= pivot) {
i++;
}
if (i < j) {
arr[j--] = arr[i];
}
}
arr[i] = pivot;
return i;
}
}
```
阅读全文