两种交换排序总结 冒泡排序 快速排序

交换排序总结

1.冒泡排序
算法特点:
1.稳定排序
2.可用于链式结构
3.移动记录次数较多,算法平均时间性能比直接插入排序差。当初始记录无序,n较大时,不宜采用。
4.时间复杂度O(n*n)空间复杂度O(1);

#include <iostream>
#include<bits/stdc++.h>
using namespace std;

void  BubbleSort(int *a,int length){
    
    
    int flag;
    for(int i=0;i<length;i++){
    
    
            flag=0;
    for(int j=0;j<length-i;j++){
    
    
        if(a[j]>a[j+1]){
    
    
            int t=a[j];
            a[j]=a[j+1];
            a[j+1]=t;
            flag=1;
        }
    }
    if(flag==0) break;
    }

}
int main()
{
    
    

    int a[10]={
    
    49,38,65,97,76,13,27,49,55,04};
   BubbleSort(a,10);
    for(int i=0;i<10;i++)
    cout <<a[i]<<" ";
    return 0;
}

2.快速排序
算法特点:
1.记录的非顺序移动导致排序方法是不稳定的。
2.排序过程中需要定位表的上界和下界,所以适合顺序结构,很难用于链式结构。
3.当n较大时,在平均情况下快速排序是所有内部排序方法中速度最快的一种,所以适合初始记录无序,n较大的情况。
4.平均情况下,时间复杂度为O(nlogn);空间复杂度最坏为O(n),最好为O(logn);

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int Partition(int *a,int low,int high){
    
    
    int t;
    t=a[low];
    while(low<high){
    
    
        while(low<high&&t<=a[high]) high--;
        a[low]=a[high];
        while(low<high&&t>=a[low]) low++;
        a[high]=a[low];
    }
    a[low]=t;
    return low;
}
void QSort(int a[],int low,int high){
    
    
    if(low<high){
    
    
        int pivotloc=Partition(a,low,high);
        QSort(a,low,pivotloc-1);
        QSort(a,pivotloc+1,high);
    }
}
int main()
{
    
    

    int a[10]={
    
    49,38,65,97,76,13,27,49,55,04};
   QSort(a,0,9);
    for(int i=0;i<10;i++)
    cout <<a[i]<<" ";
    return 0;
}

猜你喜欢

转载自blog.csdn.net/changbaishannefu/article/details/111500229