2011.04.06 10个数排序问题

来源:互联网 发布:淘宝店铺贷款平台 编辑:程序博客网 时间:2024/06/03 17:44

给定的10个数字排序,这是个最基本的问题了。

最基本的方法:

#include <iostream>

using namespace std;

 

int main()

{

int a[10] = {1,5,9,8,2,3,4,6,7,10};

for (int i=0; i<10; i++)

{

for (int j=i+1; j<10; j++)

{

if (a[j] < a[i])

{

int temp = a[j];

a[j] = a[i];

a[i] = temp;

}

}

}

for (int i=0; i<10; i++)

{

cout<<a[i]<<" ";

}

cout<<endl;

return 0;

}

输出:1 2 3 4 5 6 7 8 9 10

这个是最基本的方法,利用指针作比较,就是传说中的冒泡法。

后来看stl,发现用vector真的很简单,毕竟人家已经把算法封装好了。

并且,用stl的时候还不用担心,溢出问题,容器自动增长。

初试stl:

#include <iostream>

using namespace std;

#include <vector>

#include <iterator>

#include <algorithm>

 

int main()

{

int a[10] = {1,5,9,2,4,6,8,3,7,10};

vector<int> vectorInt(a, a+10);

sort(vectorInt.begin(), vectorInt.end());

vector<int>::iterator vectorIt;

for (vectorIt=vectorInt.begin(); vectorIt!=vectorInt.end(); ++vectorIt)

{

cout<<*vectorIt<<" ";

}

cout<<endl;

return 0;

}

输出:1 2 3 4 5 6 7 8 9 10

放在这里留着自己看,以后面试题可能会在此碰见。

高手看见,千万别笑话我的菜啊~~

 

 

(vs05下编译通过)