冒泡排序:每次遍历中,比较连续相邻的元素,如果某一对元素是降序,则互换它们的值
//冒泡排序 O(n2)
public static void BubbeSort(int[] list){
boolean needNextPass = true;
for(int k=1;k<list.length && needNextPass;k++) {
needNextPass = false;//如果遍历中没有发生交换,就不必进行下次遍历
for(int i=0;i<list.length-k;i++) {
if(list[i]>list[i+1]) {
int temp = list[i];
list[i]=list[i+1];
list[i+1]=temp;
needNextPass = true;
}
}
}
}
归并排序:算法将数组分为两半,对每部分递归地应用归并排序,在两部分都排好序之后,对它们进行归并。
//归并排序
//1.归并两个有序数组
public static int[] merge(int[] list1,int[] list2) {
int[] temp = new int[list1.length+list2.length];
int current1=0;
int current2=0;
int current3=0;
while(current1<list1.length&¤t2<list2.length) {
if(list1[current1]<list2[current2])
temp[current3++] = list1[current1++];//先赋值,后自增,所以储存的是下标0的元素
else
temp[current3++] = list2[current2++];
}
while(current1<list1.length)
temp[current3++] = list1[current1++];
while(current2<list2.length)
temp[current3++] =list2[current2++];
return temp;
}
public static void mergeSort(int[] list) {//复杂度为O(nlogn)
if(list.length>1) {
int[] firstHalf = new int[list.length/2];
//arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
//src表示源数组,srcPos表示源数组要复制的起始位置,desc表示目标数组,length表示要复制的长度。
System.arraycopy(list, 0, firstHalf, 0, list.length/2);
mergeSort(firstHalf);
int secondHalfLenth = list.length-list.length/2;
int[] secondHalf = new int[secondHalfLenth];
System.arraycopy(list, list.length/2, secondHalf, 0, secondHalfLenth);
mergeSort(secondHalf);
int[] temp = merge(firstHalf,secondHalf);
System.arraycopy(temp, 0, list, 0, temp.length);
}
}
快速排序:在数组中选择一个主元(privot)的元素,将数组分为两部分,使得第一部分的所有元素搜小于或等于主元,第二部分中的所有元素都大于主元素,对第一部分递归地应用排序算法,然后对第二部分递归地应用排序算法
//快速排序
public static void quickSort(int[] list) {
quickSort(list,0,list.length-1);
}
private static void quickSort(int[] list, int first, int last) {
if(last>first) {
int pivotIndex = partition(list, first, last);
quickSort(list,first,pivotIndex-1);
quickSort(list,pivotIndex+1,last);
}
}
/*Partition(分割) the array list[first...last]*/
public static int partition(int[] list,int first,int last) {
int pivot = list[first]; //Choose the first element as the pivot
int low = first+1; //Index for forward search
int high = last; //Index for backward search
while(high>low) { //条件满足执行
while(low<=high && list[low]<=pivot)
low++;
while(low<=high && list[high]>pivot)
high--;
if(high>low) {
int temp = list[high];
list[high] = list[low];
list[low] = temp;
}
}
while(high>first && list[high]>=pivot) {
high--;
}
if(pivot>list[high]) {
list[first]=list[high];
list[high]=pivot;
return high;
}else {
return first;
}
}