用java 写一个排序算法
时间: 2024-05-03 11:23:14 浏览: 17
以下是一个简单的选择排序算法的Java实现:
```java
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;
}
}
```
该算法的时间复杂度为O(n^2),其中n是数组的长度。它的基本思想是,每次从未排序的部分中选择最小的元素,并将其与未排序部分的第一个元素交换位置,以此类推,直到整个数组都被排序。
相关问题
用java写一个排序算法
以下是使用Java实现冒泡排序算法的示例代码:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 4, 9, 1};
bubbleSort(arr);
for (int num : arr) {
System.out.print(num + " ");
}
}
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;
}
}
}
}
}
```
该示例代码使用冒泡排序算法对整数数组进行排序。算法的基本思想是重复地遍历要排序的数组,比较相邻的元素并交换它们的位置,直到整个数组都有序。在上面的实现中,`bubbleSort()`方法接受一个整数数组作为输入参数,并使用两个嵌套的循环来实现冒泡排序。内部循环比较相邻的元素并交换它们的位置,外部循环重复这个过程直到整个数组都有序。最终,数组中的元素按升序排列。
用Java写一个排序算法
这里给出一个简单的冒泡排序算法示例:
```java
public class BubbleSort {
public static void main(String[] args) {
int[] nums = {3, 7, 1, 4, 2, 6, 5};
bubbleSort(nums);
for (int num : nums) {
System.out.print(num + " ");
}
}
public static void bubbleSort(int[] nums) {
int len = nums.length;
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (nums[j] > nums[j + 1]) {
int tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
}
}
}
}
}
```
以上是简单的冒泡排序,还有许多其他的排序算法,如快速排序、归并排序、选择排序等等,可以根据实际情况选择使用。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![mht](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)