最近学了几个排序算法,为了加深印象,现在写下来思路。希望各位朋友指正。
1.直接插入排序
直接插入排序是将元素插入到已经排好序的队列中。
public static void insertSort(int[] a) {
for (int i = 0; i < a.length; i++) {
int temp = a[i];
int j = i - 1;
for (j = i - 1; j >= 0; j--) {
if (a[j] > temp) {
a[j + 1] = a[j];
} else {
break;
}
}
a[j + 1] = temp;
}
}
时间复杂度是o(n^2),另外需要一个单位的辅助存储空间
2.冒泡排序
冒泡排序是交换排序的一种,它是两两之间进行大小比较,如果不符合的话就交换位置。
public static void Bubble(int [] a)
{
for (int i = 0; i < a.length; i++) {
for (int j = 0; j+1 < a.length; j++) {
int temp=0;
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
冒泡排序的时间复杂度o(n^2),也需要一个单位的额外存储空间。
3.选择排序
选择排序也属于交换排序的一种,只不过它不是两两比较交换,而是要全部进行比较
public static void Selectsort(int [] a)
{
for (int i = 0; i < a.length; i++) {
int min=i;
for (int j = i; j < a.length-1; j++) {
if(a[j+1]<a[min])
{
min=j+1;
}
}
if(a[min]<a[i])
{
int temp=a[min];
a[min]=a[i];
a[i]=temp;
}
}
}
选择排序的时间复杂度也是o(n^2),也需要额外一个单位的辅助存储空间。
4.快速排序
快速排序算法是给每个元素在一次迭代中找到合适的定位。运用的是递归思想。
public static int fast(int low,int high)
{
int p=a[low];
while(low<high)
{
while(low<high&&a[high]>p)
{
high--;
}
if(low<high)
{
a[low]=a[high];
low++;
}
while(low<high&&a[low]<p)
{
low++;
}
if(low<high)
{
a[high]=a[low];
high--;
}
}
a[low]=p;
return low;
}
public static void main(String[] args) {
int low=0;
int high=a.length-1;
if(low<high)
{
int p=fast(low,high);
fast(low,p-1);
fast(p+1,high);
}
}
快速排序的时间复杂度是o(nlog2(n))