冒泡排序
/**
* 冒泡排序
*/
private static void bubbleSort(int[] arr) {
int temp;
for (int j = 0; j < arr.length - 1; j++) {
//每一轮都和旁边的元素做比较
for (int i = 0; i < arr.length - 1 - j; i++) {
if (arr[i] > arr[i + 1]) {
//交换
temp = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
选择排序
/**
* 选择排序
*/
private static void selectSort(int[] arr) {
int length = arr.length;
int temp;
for (int j = 0; j < length - 1; j++) {
//每一轮都挨个比较
for (int i = j; i < length - 1; i++) {
if (arr[j] > arr[i + 1]) {
//交换
temp = arr[j];
arr[j] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
完整代码
public class Main {
public static void main(String[] args) {
int[] arr1 = {2, 3, 6, 4, 0, 1, 7, 8, 5, 9};
int[] arr2 = {2, 3, 6, 4, 0, 1, 7, 8, 5, 9};
bubbleSort(arr1);
System.out.println("----------------------------");
selectSort(arr2);
}
/**
* 冒泡排序
*/
private static void bubbleSort(int[] arr) {
int temp;
for (int j = 0; j < arr.length - 1; j++) {
//每一轮都和旁边的元素做比较
for (int i = 0; i < arr.length - 1 - j; i++) {
if (arr[i] > arr[i + 1]) {
//交换
temp = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
/**
* 选择排序
*/
private static void selectSort(int[] arr) {
int length = arr.length;
int temp;
for (int j = 0; j < length - 1; j++) {
//每一轮都挨个比较
for (int i = j; i < length - 1; i++) {
if (arr[j] > arr[i + 1]) {
//交换
temp = arr[j];
arr[j] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
网友评论