第1个回答 2010-11-30
#include <iostream>
using namespace std;
void fun(int *x, int n)
{
if (n <= 0)
return;
else if (n == 1)
{
cout << x[0] << endl;
return;
}
else if (n == 2)
{
if (x[0] < x[1])
cout << x[1] << " " << x[0] << endl;
return;
}
int max1 = x[0], max2 = x[0];
int t, j = 0, k = 0;
for (int i = 1; i < n; ++i)
{
if (x[i] > max1)
{
max2 = max1;
max1 = x[i];
k = j;
j = i;
}
}
t = x[1];
x[1] = x[k];
x[k] = t;
t = x[0];
x[0] = x[j];
x[j] = t;
for (int i = 0; i < n; ++i)
cout << x[i] << " ";
cout << endl;
}
void main()
{
int *array;
int len;
cout << "请输入数组的长度:(至少>=2,否则没效果)" << endl;
cin >> len;
array = new int[len];
cout << "请输入数组的各个元素:" << endl;
for (int i = 0; i < len; ++i)
cin >> array[i];
fun(array, len);
}
ps:数组长度可由用户来输入确定。
第2个回答 2010-11-30
#include <stdio.h>
void fun(int *x,int n)
{
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<(n-1-i);j++)
if(*(x+j)>*(x+j+1))
{
k=*(x+j);
*(x+j)=*(x+j+1);
*(x+j+1)=k;
}
for(i=0;i<2;i++)
{
k=*(x+n-1-i);
*(x+n-1-i)=*(x+i);
*(x+i)=k;
}
}
void main()
{
int i, a[10];
for(i=0;i<10;i++)
scanf("%d",&a[i]);
fun(a,10);
for(i=0;i<10;i++)
printf("%3d",a[i]);
}
希望能帮助你!
第3个回答 2010-11-30
#include <iostream>
using namespace std;
void fun( int *x, int n )
{
int nloop;
int nTmp, nMax = *x, nMaxIndex, nTMax = *x, nTMaxIndex;
for( nloop = 1; nloop < n; nloop++ )
{
if( nMax < *( x + nloop ) )
{
nMaxIndex = nloop;
nMax = *( x + nloop );
}
//if( nTMax >= nMax ) nTMax = *( x + nloop );
if( ( nTMax < *( x + nloop ) ) && ( nMax > *( x + nloop ) ) )
{
nTMaxIndex = nloop;
nTMax = *( x + nloop );
}
}
nTmp = *x;
*x = nMax;
*( x + nMaxIndex ) = nTmp;
nTmp = *( x + 1 );
*( x + 1 ) = nTMax;
*( x + nTMaxIndex ) = nTmp;
}
void main( void )
{
int nloop;
int nSort[] = { 2, 4, 6, 1, 3, 9, 7, 0, 5, 8 };
fun( nSort, 10 );
for( nloop = 0; nloop < 10; nloop++ )
{
cout << nSort[ nloop ] << ", ";
}
cout << endl;
cin.get();
}本回答被网友采纳