冒泡排序
private static void bubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
}
选择排序
public static void selectionSort(int[] arr) {
int temp, min = 0;
for (int i = 0; i < arr.length - 1; i++) {
min = i;
// 循环查找最小值
for (int j = i + 1; j < arr.length; j++) {
if (arr[min] > arr[j]) {
min = j;
}
}
if (min != i) {
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}
插入排序
public static void insertionSort(int[] arr){
for (int i=1; i<arr.length; ++i){
int value = arr[i];
int position=i;
while (position>0 && arr[position-1]>value){
arr[position] = arr[position-1];
position--;
}
arr[position] = value;
}//loop i
}
归并排序
public static void mergeSort(int[] arr, int left, int right, int[] temp) {
if (left < right) {
//中间索引
int mid = (left + right) / 2;
//向左递归进行分解
//0 - mid 即是0 - 3 {8,4,5,7}
mergeSort(arr, left, mid, temp);
//向右递归进行分解
//mid+1 - midright 即是4 - 7 {1,3,6,2}
mergeSort(arr, mid + 1, right, temp);
//进行合并
merge(arr, left, mid, right, temp);
}
}
public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
int i = left;
int j = mid + 1;
int k = 0;
while (i <= mid && j <= right) {
temp[k++] = arr[i] <= arr[j] ? arr[i++] : arr[j++];
}
while (i <= mid) {
temp[k++] = arr[i++];
}
while (j <= right) {
temp[k++] = arr[j++];
}
//把数据复制回原数组
for (i = 0; i < k; ++i) {
arr[left + i] = temp[i];
}
}