写一个Java排序程序
下面是一个简单的Java排序程序,使用冒泡排序算法:
public class Sort {
public static void main(String[] args) {
int[] arr = {5, 3, 8, 6, 4, 2};
bubbleSort(arr);
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
public static void bubbleSort(int[] arr) {
int temp;
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]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}
这个程序使用了冒泡排序算法,首先定义了一个数组,然后调用bubbleSort方法对数组进行排序。bubbleSort方法使用了双重循环,外层循环控制排序的轮数,内层循环控制每一轮排序的比较次数。如果相邻两个元素的值大小关系不正确,则交换它们的位置。最后在main方法中输出排序结果
原文地址: https://www.cveoy.top/t/topic/hrFb 著作权归作者所有。请勿转载和采集!