冒泡排序:
public static void bubbleSort(double[] arrs) {
double temp = 0;
//外层,总共需要走几趟
for(int i = 0; i < arrs.length-1; i++) {
//内层,每一趟都逐渐少排一个数
for (int j = 0; j < arrs.length-1-i; j++) {
if(arrs[j] > arrs[j+1]) {
temp = arrs[j+1];
arrs[j+1] = arrs[j];
arrs[j] = temp;
}
}
}
}
选择排序:
public static void selectSort(double[] arrs) {
double min = 0;
int minIndex = 0;
//需要走几趟
for (int i = 0; i < arrs.length-1; i++) {
//设置第i个树为最小值
min = arrs[i];
minIndex = i;
//从第i+1个数开始查找最小值
for (int j = i+1; j < arrs.length; j++) {
if(min > arrs[j]){
min = arrs[j];
minIndex = j;
}
}
//最小值与第i个数交换
double temp = arrs[i];
arrs[i] = arrs[minIndex];
arrs[minIndex] = temp;
}
}
插入排序:
public static void insertSort(double[] arrs) {
//从第2个数开始插入排序
for (int i = 1; i < arrs.length; i++) {
double insertValue = arrs[i];
int index = i-1;
//找出第后面未排序的数字中在以排序数组中的位置,并后移
while(index >= 0 && insertValue < arrs[index]) {
arrs[index+1] = arrs[index];
index--;
}
arrs[index+1] = insertValue;
}
}
快速排序:
public static void quickSort(double[] arrs, int low, int high) {
int start = low;
int end = high;
//基准值
double key = arrs[low];
double temp = 0;
while(start < end) {
//找到右边比基准值小的值,如果不小于,往前移动;如果小于,和当前的low位置交换
while(start < end && arrs[end] >= key) end--;
if(key > arrs[end]){
temp = arrs[start];
arrs[start] = arrs[end];
arrs[end] = temp;
}
//找到左边比基准值大的值,如果不大于,往后移动;如果大于,和当前的high位置交换
while(start < end && arrs[start] <= key) start++;
if(key < arrs[start]){
temp = arrs[start];
arrs[start] = arrs[end];
arrs[end] = temp;
}
}
if(start > low)
quickSort(arrs, low, start-1);
if(end < high)
quickSort(arrs, end+1, high);
}