这几天又咸鱼了,写一些快排和冒泡复习一下。
不稳定排序
· 快速排序 — O(nlogn) 期望时间, O(n²) 最坏情况; 对于大的、乱数串行一般相信是最快的已知排序
稳定排序
· 冒泡排序 — O(n²)
//复习排序算法
//(一趟)快排
public int Parttition(int[] L,int low,int high) {
int pivotkey=L[low];
while(low<high) {
while(low<high&&L[high]>pivotkey) {
--high;
}
L[low]=L[high];
while(low<high&&L[low]<=pivotkey) {
++low;
}
L[high]=L[low];
}
L[low]=pivotkey;
return low;
}
//快排,递归
public void QuickSort(int[] L,int low,int high) {
if(low<high) {
int pivotloc=Parttition(L,low,high);
QuickSort(L,low,pivotloc-1);
QuickSort(L,pivotloc+1,high);
}
}
//冒泡排序,标准版(经优化)
public void BubbleSort1(int[] a,int n) {
boolean flag=true;
int i,k=n;
while(flag) {
flag=false;
for(i=0;i<k-1;i++) {
if(a[i]>a[i+1]) {
int temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
flag=true;
}
}
k--;
}
}
public static void main(String[] arg) {
SortBlog sortblog=new SortBlog();
//快排
int[] L= {0,2,1,6,4,5,7,9,10,8,3};
System.out.println("排序前:");
for(int i=0;i<L.length;i++) {
System.out.print(L[i]+" ");
}
sortblog.QuickSort(L,0,L.length-1);
System.out.println("\n"+"快速排序后:");
for(int i=0;i<L.length;i++) {
System.out.print(L[i]+" ");
}
//冒泡1
int[] L1= {0,2,1,6,4,5,7,9,10,8,3};
System.out.println("\n"+"排序前:");
for(int i=0;i<L1.length;i++) {
System.out.print(L1[i]+" ");
}
sortblog.BubbleSort1(L1,L1.length);
System.out.println("\n"+"冒泡排序1后:");
for(int i=0;i<L1.length;i++) {
System.out.print(L1[i]+" ");
}
}
}