将顺序表元素从大到小排序输出
顺序表长度:
6
输入元素:
45 23 78 2 12 6
输出:
45 23 78 2 12 6
排序后输出:
78 45 23 12 6 2
----------------------------------------
#include <iostream>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MaxSize 100
using namespace std;
typedef int ElemType;
typedef int Status;
//定义
typedef struct
{
ElemType *Elem; //动态数组,存储空间基地址
int length ; //当前长度
}SqList; //顺序表结构类型
//初始化
Status InitList(SqList &L)
{ //构造一个空的顺序表
L.Elem = new ElemType[MaxSize]; //为顺序分配一个MAxSize大小的空间
if (!L.Elem) //判断是否成功分配到空间
exit(OVERFLOW);
else
L.length = 0;
return OK;
}
//创建
Status CreatList(SqList &L, int n) //创建一个长度为n的顺序表
{
for (int i = 0; i < n ; i++)
cin >> L.Elem[i];
L.length = n;
return OK;
}
//输出
Status DispList(SqList L)
{
for (int i = 0; i < L.length; i++)
cout << L.Elem[i] << ' ';
return OK;
}
//排序
void func(SqList L)
{
int i, j , temp;
for (i = 1; i < L.length; i++)
{
temp = L.Elem[i]; //temp初始化为第二个元素(也就是数组下标为1的元素值)
j = i - 1; //j初始化为第一个元素下标
while (j >= 0 && temp > L.Elem[j]) //如果j大于0,将第一个元素跟第二个元素相比较,如果后一个元素大于前一个
{
L.Elem[j + 1] = L.Elem[j]; //就将两个元素交换位置
j--; //j--
}
L.Elem[j + 1] = temp; //否则,不改变该位置的元素值
}
}
int main()
{
int n;
SqList L;
InitList(L);
cout << "顺序表长度:" << endl;
cin >> n ;
cout << "输入元素:" << endl;
CreatList(L, n);
cout << "输出:" << ' ' << endl;
DispList(L);
cout << endl;
cout << "排序后输出:" << endl;
func(L);
DispList(L);
return 0;
}
04-04
2103
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交