数据结构-排序-起泡排序-简单排序

                    起泡排序

  首先起泡排序同样分有序区和无序区。基本思想:两两比较,反序则交换位置。

  由于这个特性我们就知道,一趟排序后,最后一个必然是最大的。然后第二次最后第二大又找到。

  然后就很简单了直接上代码。虽然代码很简单,但是里面设计却很巧妙

  

#include<iostream>
#include<vecotr>
using namespace std;
//不含暂存单元的数组v1
int temp1[]={59,20,17,36,98,14,23,83,13,28};
vector<int>  v1(begin(temp1),end(temp1));
//打印数组
inline void  printV(const vector<int> &v)
{
    for(auto a:v)
        cout<<a<<" ";
    cout<<endl;
}
//起泡排序
void bubble_sort(vector<int> &v)
{
    cout<<"起泡排序"<<endl;
    int exchange=v.size();             //定义排序区间
    while(exchange!=0)    //当上一趟排序有交换时候
    {
        int bound=exchange;
        exchange=0;       //这里设置为0假如下面for循环没有改变值说明都是正序了就退出
        for(int i=0;i<bound-1;i++)    //bound后面都是正序了bound-1还是乱序的
        {
            if(v[i]>v[i+1])//假如反序则交换,且把exchange设置为i+1
            {
                int temp=v[i];    
                v[i]=v[i+1];
                v[i+1]=temp;
                exchange=i+1;
                cout<<"交换位"<<exchange<<endl;
                printV(v);
            }
        }
    }
}



int main(int argc, char *argv[])
{
    printV(v);
    bubble_sort(v);
    return 0;
}
                

同样贴上打印的数据,每次交换都有

                  简单排序

  简单排序很气泡排序个人感觉很类似,起泡是每次遍历后最后一个最大,简单排序是每次遍历后把最小的插入第一个或者最后一个,或者选最大的也可以。优点是插入次数很少,缺点也很明显,数据量一大,这个算法就废了。

  过于简单直接上代码了

  

#include<iostream>
#include<vector>
using namespace std;
//不含暂存单元的数组v1
int temp1[]={59,20,17,36,98,14,23,83,13,28};
vector<int>  v1(begin(temp1),end(temp1));
//打印数组
inline void  printV(const vector<int> &v)
{
    for(auto a:v)
        cout<<a<<" ";
    cout<<endl;
}

//简单选择排序
void selectedSort(vector<int>& v)
{
    for(int i=0;i<v.size();i++)            //i是边界
    {
        int index=i;//用来保存无序区的最小值
        int j=0;
        for(j=i+1;j<=v.size();j++)//遍历无序区间
        {
            if(v[j]<v[index])
                index=j;            //假如无序区间有小于index的值就把index设为j
            if(index!=i)            //然后交换index和i的值
            {
                int temp=v[i];
                v[i]=v[index];
                v[index]=temp;
            }
        }
    }
}
int main(int argc, char *argv[])
{
    selectedSort(v1);
    printV(v1);
    return 0;
}
转载请标明出处
原文地址:https://www.cnblogs.com/DJC-BLOG/p/9068989.html