基本思路:比较表中的相邻元素,如果他们是逆序的话就交换他们的位置。重复多次以后,最终最大
的元素就沉到列表的最后一个位置,第二遍操作将第二大的元素沉下去,这样一直做,知道n-1遍以后,该列表就排好序了。
代码如下:
-
#include<stdio.h>
-
#include<malloc.h>
-
#include<iostream>
-
using namespace std;
-
//#define swap(x,y) (x ^= y,y ^= x,x ^= y)
-
int minTime(int *a,int n){
-
if (a ==NULL || n == 0)
-
return 0;
-
int i = 0,j = 0;
-
int count = 0;
-
for (i = 0;i < n-1;i++)
-
{
-
for (j = 0;j < n-i-1;j++)
-
{
-
if (a[j] > a[j+1])
-
{
-
swap(a[j],a[j+1]);
-
count++;
-
}
-
-
}
-
}
-
return count;
-
}
-
int main()
-
{
-
-
int len = 0;
-
while (cin >> len)
-
{
-
int *a = (int *)malloc(sizeof(int)*len);
-
int i = 0;
-
for (i = 0;i < len;i++)
-
{
-
cin >> a[i];
-
}
-
int result = minTime(a,len);
-
printf("%d\n",result);
-
for (i = 0;i < len;i++)
-
{
-
printf("%d\n",a[i]);
-
}
-
free(a);
-
}
-
return 0;
-
}
包括比较次数
运行结果如下:
[root@localhost ~]# ./a.out
4
4 3 2 1
6
1
2
3
4
去哪笔试题(2016.09.08)
-
#include<iostream>
-
#include<vector>
-
using namespace std;
-
class Coder {
-
public:
-
vector<string> findCoder(vector<string> A, int n) {
-
vector<string> result;
-
vector<int> resultInt;
-
//int count = 0;
-
vector<string>::iterator iter = A.begin();
-
for (;iter != A.end();iter++)
-
{
-
int j =0;
-
string s = *iter;
-
int count = 0;
-
for (int i = 0;i < (*iter).length() && i+4 < (*iter).length();)
-
{
-
if (toupper(s[i]) == 'C' && toupper(s[i+1]) == 'O' && toupper(s[i+2]) == 'D' && toupper(s[i+3]) == 'E' && toupper(s[i+4]) == 'R')
-
{
-
i = i+5;
-
count++;
-
}
-
else
-
i = i+1;
-
}
-
//cout << count << endl;
-
result.push_back(*iter);
-
resultInt.push_back(count);
-
}
-
for (int i = 0;i < n-1;i++)
-
{
-
for (int j = 0;j < n-i-1;j++)
-
{
-
if (resultInt[j] < resultInt[j+1])
-
{
-
swap(resultInt[j],resultInt[j+1]);
-
swap(result[j],result[j+1]);
-
}
-
}
-
}
-
for (int i = 0;i < n;i++)
-
{
-
cout << result[i]<< endl;
-
cout << resultInt[i]<< endl;
-
}
-
return result;
-
}
-
};
-
int main()
-
{
-
Coder coder;
-
string str[3] = {"i am a coder","Coder,Coder","Coder"};
-
vector<string> A(&str[0],&str[3]);
-
coder.findCoder(A,3);
-
return 0;
-
}
运行结果:
[root@bogon ~]# ./a.out
Coder,Coder
2
i am a coder
1
Coder
1
[root@bogon ~]#
阅读(787) | 评论(0) | 转发(0) |