读书人

关于排序,该如何处理

发布时间: 2012-02-08 19:52:21 作者: rapoo

关于排序
输入几个数,按以下要求排序
如输入;5//排序数个数
3 5 1 7 9//排序数
排序方法;找数中最小的1写入数组第一个数,
找数中最小的(已排的除外)3写入数组第二个数;
......
输出1 3 5 7 9

[解决办法]
应该这样,刚才忘记释放内存了
#include <iostream.h>

template <class T>
void Swap (T &x, T &y)
{ T temp;
temp = x;
x = y;
y = temp;
}
template <class T>
void SelectionSort(T A[], int n)
{ int smallIndex;
int i, j;
for (i = 0; i < n-1; i++)
{ smallIndex = i;
for (j = i+1; j < n; j++)
if (A[j] < A[smallIndex]) smallIndex = j;
Swap(A[i], A[smallIndex]);
}
}

void main()
{
int i,j,k;
int num=0;

cout < < "排序数个数: ";
cin> > num;
int *a=new int[num];

for(i=0;i <num;i++)
{
cout < < "请输入第 " < <i+1 < < "个数: ";
cin> > a[i];
}
cout < <endl;
SelectionSort(a,num);

for(i=0;i <num;i++)
{
cout < <a[i] < < " ";
}
cout < <endl;
delete []a;
}
[解决办法]
#include "stdlib.h "
#include "stdio.h "

int main()
{
int data[128];
int len = 0;
int t = 0;

printf( "enter number count : ");
scanf( "%d ", &len);

printf( "enter number list : ");
while (t < len)
scanf( "%d ", &data[t++]);

t = 0;

while (t < len - 1)
{
int s = len;
while (--s > t)
{
if (data[s] < data[s - 1])
{
int temp = data[s];
data[s] = data[s - 1];
data[s - 1] = temp;
}
}
t++;
}

t = 0;
while (t < len)
printf( "%d ", data[t++]);


return 0;
}
[解决办法]
#include <stdio.h>
#define M 100
main()
{ int m,a[M],i,j,t;
printf( "Input the number:\n ");
scanf( "%d ",&m);
printf( "\n ");
printf( "Input the shuzu:\n ");
for(i=0;i <m;i++)
scanf( "%d ",&a[i]) ;
clrscr();
for(i=0;i <m-1;i++)
for(j=i;j <m;j++)
if(a[i]> a[j])
{t=a[i];a[i]=a[j];a[j]=t;}
printf( "input the new shuzu:\n ");
for(i=0;i <m;i++)
printf( "%5d ",a[i]);}
保证能运行成功 !!!

读书人网 >C语言

热点推荐