JavaSE中的几种排序方式,思想远比代码重要,面试常用:
//冒泡排序
public class BubbleSort {
public static void bubbleSort(int[] arr){
//外循环控制比较的次数
for (int i : arr) {
//内循环控制每次比较中,元素两两比较的过程.每次需要比较的数据是逐渐减少
for (int j = 0; j < arr.length-1; j++) {
//比较相邻元素,如果前面的大,进行交换
if (arr[j]>arr[j+1]) {
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
}
//选择排序
public static void selectSort(int[] arr){
for(int i=0; i<arr.length-1; i++){
for(int j=i+1; j<arr.length; j++){
if(arr[i] < arr[j]){
int temp = arr[j];
arr[j] = arr[i];
arr[i] =temp;
}
}
}
}