冒泡排序和插入排序算法是两个简单易实现的排序算法,但工作效率低下,只适合做小规模数据的排序。
冒泡排序:根据自己的需求,每次排序时把序列中最大的数置于序列首或序列尾,经过多次排序得到有序序列。
#include <iostream>
using namespace std;
int main()
{
void bubble_sort(int sample[]);
int array[10];
cout<<"please give sample array(size:10):"<<endl;
for (int i=0; i!=10; i++)
{
cin>>array[i];
}
bubble_sort(array);
for (int i=0; i!=10; i++)
{
cout<<array[i]<<" "<<flush;
}
}
void bubble_sort(int sample[])
{
int mark;
int times;
int temp;
for (times=0; times<=9; times++)
{
for (mark=0; mark+times<9; mark++)
{
if (sample[mark]>=sample[mark+1])
{
temp=sample[mark+1];
sample[mark+1]=sample[mark];
sample[mark]=temp;
}
}
}
}
插入排序:每次输入数据时,将数据插入到序列中合适的位置,得到有序序列。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> base;
int main()
{
int data;
void Insertion_sort(int input);
void display();
cout<<" please enter data(press s to finish):"<<endl;
cin>>data;
base.push_back(data);
while(cin>>data)
{
Insertion_sort(data);
}
display();
}
void Insertion_sort(int input)
{
auto beg=base.begin();
auto end=base.end();
while(*beg>=input && beg!=end)
{
beg++;
}
base.insert(beg,input);
}
void display()
{
auto beg=base.begin();
auto end=base.end();
while(beg!=end)
{
cout<<*beg++<<" "<<flush;
}
}