用户输入数组内容按降序输出
用户输入数组内容按升序输出这个程序要怎么写 这不就是排序吗?到底要升序,还是降序?给你一个冒泡排序算法程序
#include <stdio.h>
void shengxu(int a[],int len)
{
int i,j,temp;
for(i = 0;i < len - 1;i++){
for(j = len - 1;j > i;j--)
if (a < a){
temp = a;
a = a;
a = temp;
}
}
}
void jiangxu(int a[],int len)
{
int i,j,temp;
for(i = 0;i < len - 1;i++){
for(j = len - 1;j > i;j--)
if (a > a){
temp = a;
a = a;
a = temp;
}
}
}
int main()
{
int i;
int a;
int length;
length = sizeof(a)/sizeof(a);
for (i=0;i<length;i++)
scanf("%d",&a);
shengxu(a,length);
for(i = 0;i<length;i++)
printf("%d",a);
printf("\n");
jiangxu(a,length);
for(i = 0;i<length;i++)
printf("%d",a);
printf("\n");
return 0;
} C++ STL标准库Algorithm库中有排序函数可供参考。// sort algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::sort
#include <vector> // std::vector
bool myfunction (int i,int j) { return (i<j); }
struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;
int main () {
int myints[] = {32,71,12,45,26,80,53,33};
std::vector<int> myvector (myints, myints+8); // 32 71 12 45 26 80 53 33
// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)
// print out content:
std::cout << "myvector contains:";
for (std::vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
页:
[1]