写了一个快速排序算法,但是不知道为啥按原序输出的
问题描述:
问题遇到的现象和发生背景
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 20
#include<iostream>
typedef int element; // 自定义int类型element
#define list_size 10000
using namespace std;
typedef struct
{
int key;
}Redtype;
typedef struct SqList
{
element* elem;
Redtype r[MAXSIZE + 1];
int length;
};
int creatnewlist(SqList& L, int n);// 建立顺序表
int initit(SqList& L);
int initit(SqList& L) //建表初始化
{
L.elem = (int*)malloc(sizeof(int));
if (!L.elem) return -1;
L.length = 0;
return 0;
}
int creatnewlist(SqList& L, int n) // 建立顺序表
{
int i;
L.elem = (int*)malloc(sizeof(int) * list_size);
if (!L.elem) return -1;
else
{
for (i = 0; i < n; i++)
{
scanf_s("%d", &L.elem[i]);
L.length++;
}
}
return 0;
}
int Partition(SqList& L, int low, int high)
{
L.r[0] = L.r[low];
int pivotket = L.r[low].key;
while (low < high)
{
while (low < high && L.r[high].key >= pivotket)--high;
L.r[low] = L.r[high];
while (low < high && L.r[low].key <= pivotket)++low;
L.r[high] = L.r[low];
}
L.r[low] = L.r[0];
return low;
}
void QSort(SqList& L, int low, int high)
{
if (low < high)
{
int pivotloc = Partition(L, low, high);
QSort(L, low, pivotloc - 1);
QSort(L,pivotloc + 1,high);
}
}
void QuicnSort(SqList& L)
{
QSort(L, 1, L.length);
}
//void ShellSore(SqList& L, int dlat[], int t)
//{
// for (int k = 0; k < t; k++)
// printf("%d", dlat[t]);
//}
void show(SqList &L) //输出顺序表
{
int i;
for(i = 0;i<L.length;i++)
{
if(i==L.length-1) printf("%d\n", L.elem[i]);
else printf("%d ", L.elem[i]);
}
}
int main()
{
int n;
int dlat[10];
printf("请输入要排的数:");
//int len;
//scanf_s("%d", &len);
SqList L;
initit(L);
creatnewlist(L, 10);
Partition(L, 0, 8);
QSort(L, 0, 8);
QuicnSort(L);
show( L);
}
问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
答
你存数据用的elem,排序用key干嘛?操作半天是对key操作,elem动都没动,输出肯定是没变的啊