冒泡排序:遍历数组中的每个元素,一次比较两个元素,大的往后移动
public static void gulugulu(int[] num) {
int temp;
int len=num.length;
for(int i=0;i<len-1;i++) {
for(int j=0;j<len-i-1;j++) {
if (num[j+1]<num[j]) {
temp=num[j+1];
num[j+1]=num[j];
num[j]=temp;
}
}
}
}
快速排序:使用分治策略,通过一个基准将他们分成两个部分,左边比他小,右边比他大。getMiddle就是用来确定这个基准的
public static int getMiddle(int[] numbers,int low,int high) {
int temp=numbers[low];
while(low<high) {
while(low<high&&temp<numbers[high]) {
high--;
}
numbers[low]=numbers[high];
while(low<high&&temp>numbers[low]) {
low++;
}
numbers[high]=numbers[low];
}
numbers[low]=temp;
return low;//返回中轴节点
}
public static void quickSort(int[] numbers,int low,int high) {
if (low<high) {
int middle=getMiddle(numbers, low, high);
quickSort(numbers, low, middle-1);//左边小的
quickSort(numbers, middle+1, high);
}
}
选择排序:遍历找到最小的加入进去,然后次小的
public static void selectSort(int[] num) {
int t;
for(int i=0;i<num.length;i++) {
int index=i;
for(int j=i+1;j<num.length;j++) {
if (num[index]>num[j]) {
index=j;
}
}
if (index!=i) {
t=num[i];
num[i]=num[index];
num[index]=t;
}
}
}
插入排序:从头开始,前面都是排好序的,找到一个元素的合适位置,数组整体移动,插入进去
public static void charu(int[] array) {
int temp;
for(int i=1;i<array.length;i++) {
temp=array[i];
while(i>=1&&array[i-1]>temp) {
array[i]=array[i-1];
i--;
}
array[i]=temp;
}
}