利用静态查找表起泡排序、快速排序
输入:输入包括多行,每行代表一定的含义
输入1,创建静态查找表,接着输入n表示查表中元素个数,再输入n个学生记录(学号、年龄、姓名)
输入4 1,代表使用起泡排序,按照学号升序排序;
输入4 -1,代表使用起泡排序,按照学号降序排序;
输入5 1,代表使用快速排序,按照学号升序排序;
输入5 -1,代表使用快速排序,按照学号降序排序;
输入0,程序结束。
输出
按照输入的顺序依次输出相关信息。
样例输入
1 3 101 22 alice 105 20 eric 102 18 david 4 1 0
样例输出
101 22 alice 102 18 david 105 20 eric
#include <stdio.h>
#include<iostream>
using namespace std;
#define MAXSIZE 20 //记录最大个数
//学生结构体
typedef struct {
char name[10];
int age;
int no;
}Student;
typedef struct {
Student data[MAXSIZE + 1];//data[0]可闲置或作监视哨
int length; //顺序表长度
}SqList;
//创建顺序表
void CreateSqList(SqList& L, int n) {
L.length = n;
for (int i = 1; i <= L.length; i++) {
scanf("%d %d %s", &L.data[i].no, &L.data[i].age, L.data[i].name);
getchar();
}
}
//输出顺序表
void PrintSqList(SqList& L) {
for (int i = 1; i <= L.length; i++)
printf("%d %d %s\n", L.data[i].no, L.data[i].age, L.data[i].name);
}
void swap(SqList& L, int i, int j)
{
Student a;
a = L.data[i];
L.data[i] = L.data[j];
L.data[j] = a;
}
//按照学号起泡排序,Acc=1表示升序,Acc=-1表示降序
void BubbleSort(SqList& L, int Acc) {
int i, j;
if (Acc == 1)
{
for (i = 1; i < L.length; i++)
{
for (j = L.length - 1; j >= i; j--)
{
if (L.data[j].no > L.data[j + 1].no)
{
swap(L, j, j + 1);
}
}
}
}
if (Acc == -1)
{
for (i = 1; i < L.length; i++)
{
for (j = L.length - 1; j >= i; j--)
{
if (L.data[j].no < L.data[j + 1].no)
{
swap(L, j, j + 1);
}
}
}
}
}
//=============按照学号快速排序start=============
//一趟快速排序过程,Acc=1表示升序,Acc=-1表示降序
int Partition(SqList& L, int low, int high, int Acc) {
int pivotkey;
pivotkey = L.data[low].no;
if (Acc == 1) {
while (low < high)
{
while (low < high && L.data[high].no >= pivotkey)
high--;
swap(L, low, high);
while (low < high && L.data[low].no <= pivotkey)
low++;
swap(L, low, high);
}
}
if (Acc ==-1) {
while (low < high)
{
while (low < high && L.data[high].no <= pivotkey)
high--;
swap(L, low, high);
while (low < high && L.data[low].no >= pivotkey)
low++;
swap(L, low, high);
}
}
return low;
}
void QSort(SqList& L, int low, int high, int Acc) {
int pivotloc;
if (low < high) { //当L.data[low..high]为空或只有一个记录时无需排序
pivotloc = Partition(L, low, high, Acc); //对 L.data[low..high]] 进行一次划分,并返回枢轴位置
QSort(L, low, pivotloc - 1, Acc); //递归处理左区间
QSort(L, pivotloc + 1, high, Acc); //递归处理右区间
}
}
void QuickSort(SqList& L, int Acc) {
QSort(L, 1, L.length, Acc);
}
//=============按照学号快速排序end=============
//主函数
int main() {
int n, Acc, SortType;
SqList List, TempList;
int select;
while (scanf("%d", &select) != EOF) {
if (select == 0)
return 0;
else if (select == 1) {
scanf("%d", &n);
CreateSqList(List, n);
}
if (select == 4) {
TempList = List;
scanf("%d", &Acc);
BubbleSort(TempList, Acc);
PrintSqList(TempList);
}
if (select == 5) {
TempList = List;
scanf("%d", &Acc);
QuickSort(TempList, Acc);
PrintSqList(TempList);
}
}
return 0;
}