这个问题与我先前的问题有关(在此连结:problems when sorting an array of integers using a quicksort algorithm),我用以下方式编辑了我的解决方案:
#include "vector.h"
void QuickSort(Vector* v, size_t first, size_t last) {
size_t i = 0; size_t j = 0;
size_t pivot = 0;
if (first <= last) {
i = first; j = last;
pivot = (v->data[first] + v->data[last]) / 2;
do {
while (v->data[i] < v->data[pivot]) i++;
while (v->data[j] > v->data[pivot]) j--;
if (i <= j) {
ElemSwap(&v->data[i], &v->data[j]);
i++; j--;
}
} while (i <= j);
QuickSort(v, first, j);
QuickSort(v, i, last);
}
}
void VectorSort(Vector* v) {
if (v == NULL) {
return;
}
QuickSort(v, 0, v->size - 1);
}
int main(void) {
ElemType v[16] = { 1, 3, 2, 9, 0, 4, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1 };
Vector* pv = calloc(1, sizeof(Vector));
if (pv == NULL) {
return NULL;
}
pv->size = pv->capacity = 16;
pv->data = v;
VectorSort(pv);
return 0;
}
回想一下,elemtype.c是这样定义的:
#define _CRT_SECURE_NO_WARNINGS
#include "elemtype.h"
#include <string.h>
#include <stdlib.h>
#define _unused(x) ((void)(x))
int ElemCompare(const ElemType *e1, const ElemType *e2) {
return (*e1 > *e2) - (*e1 < *e2);
}
ElemType ElemCopy(const ElemType *e) {
return *e;
}
void ElemSwap(ElemType *e1, ElemType *e2) {
ElemType tmp = *e1;
*e1 = *e2;
*e2 = tmp;
}
void ElemDelete(ElemType *e) {
_unused(e);
}
int ElemRead(FILE *f, ElemType *e) {
return fscanf(f, "%d", e);
}
int ElemReadStdin(ElemType *e) {
return ElemRead(stdin, e);
}
void ElemWrite(const ElemType *e, FILE *f) {
fprintf(f, "%d", *e);
}
void ElemWriteStdout(const ElemType *e) {
ElemWrite(e, stdout);
}
elemtype. h的定义如下:
#ifndef ELEMTYPE_INT_H_
#define ELEMTYPE_INT_H_
#include <stdbool.h>
#include <stdio.h>
typedef int ElemType;
int ElemCompare(const ElemType *e1, const ElemType *e2);
ElemType ElemCopy(const ElemType *e);
void ElemSwap(ElemType *e1, ElemType *e2);
void ElemDelete(ElemType *e);
int ElemRead(FILE *f, ElemType *e);
int ElemReadStdin(ElemType *e);
void ElemWrite(const ElemType *e, FILE *f);
void ElemWriteStdout(const ElemType *e);
#endif // ELEMTYPE_INT_H_
现在,vector.h是:
#pragma once
#include "ElemType.h"
#include <stdlib.h>
typedef struct {
size_t capacity;
size_t size;
ElemType* data;
} Vector;
void VectorSort(Vector* v);
这个解决方案比前一个更好,问题是当我调试时,我在这些行中有一个读访问冲突:
while (v->data[i] < v->data[pivot]) i++;
while (v->data[j] > v->data[pivot]) j--;
编辑:正如用户在评论部分建议的那样,我应该写:
while (v->data[i] < pivot) i++;
while (v->data[j] > pivot) j--;
因为pivot是一个数字,而不是索引
1条答案
按热度按时间fxnxkyjh1#
你是说
pivot = (first + last) / 2
吗我不知道当pivot是起始位置和最后位置之间的平均值的地板时,尝试访问
v->data[pivot]
意味着什么。