First, the bubble sort:
public static void bubbleSort(int []arr) {
for(int i =1;i<arr.length;i++) {
for(int j=0;j<arr.length-i;j++) {
if(arr[j]>arr[j+1]) {
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
}
At best bubble sort is drained on a trip time complexity of O (n);
The worst situation is just the reverse order required cycle (n-1) times per trip required cycle (n-1-i) times a time complexity of ((n-1) * n) / 2 is O (n ^ 2)
Therefore, the average bubble sort time complexity is O (n ^ 2);
Second, choose Sort:
public void selectSort(int[] a) {
for(int i=0;i<a.length;i++){
int k=i;
for(int j=i+1;j<a.length;j++){
if(a[j]<a[k]){
k=j;
}
}
if(k>i){
int temp = a[i];
a[i]=a[k];
a[k]=temp;
}
}
}
Preferably selection sort, the worst average time complexity are: O (n ^ 2)
Third, the quick sort:
public static int[] qsort(int arr[],int start,int end) {
int pivot = arr[start];
int i = start;
int j = end;
while (i<j) {
while ((i<j)&&(arr[j]>pivot)) {
j--;
}
while ((i<j)&&(arr[i]<pivot)) {
i++;
}
if ((arr[i]==arr[j])&&(i<j)) {
i++;
} else {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
if (i-1>start) arr=qsort(arr,start,i-1);
if (j+1<end) arr=qsort(arr,j+1,end);
return (arr);
}
最坏的情况是,每次所选的中间数是当前序列中的最大或最小元素
长度为n的数据表的快速排序需要经过n趟划分,使得整个排序算法的时间复杂度为O(n^2)
理想的情况是,每次划分所选择的中间数恰好将当前序列几乎等分,经过logn趟划分,时间复杂度为O(nlogn)
平均情况下:T(n)=2*T(n/2)+n; 第一次划分
=2*(2*T(n/4)+n/2)+n; 第二次划分 (=2^2*T(n/4)+2*n)
=2*(2*(2*T(n/8)+n/4)+n/2)+n; 第三次划分(=2*3*T(n/8)+3*n)
=.....................
=2^m+m*n; 第m次划分
因为2^m=n,所以等价于 = n+m*n
所以m=logn,所以T(n)=n+n*logn;
快速排序的平均时间复杂度是O(n*logn)