快速排序的动态大量对象无法正常工作[关闭]
Posted
技术标签:
【中文标题】快速排序的动态大量对象无法正常工作[关闭]【英文标题】:Quick sort of dynamic massive of objects doesn't work correctly [closed] 【发布时间】:2018-01-12 14:48:56 【问题描述】:在我的任务中,我必须创建具有数据成员的类城市
width(GeografskaShirina)
lenght(GeografskaDaljina)
ime(name)
NadmorskaVisochina(height)
我有defalut的构造函数,它输入数据,复制构造函数和operator =的预定义。
我应该使用快速排序按 GeografskaDaljina(length) 对我的动态数组保加利亚进行排序,这是我在快速排序类的方法中实现的。我还有一个 Output() 方法(打印排序后的城市名称)方法 getDaljina(),它返回 GeografskaDaljina(length)。
问题是当我在 main() 中调用 quicksort 时,排序不能正常工作,并且不打印希望的结果。
#include "stdafx.h"
#include<string>
#include<iostream>
using namespace std;
class city
private:
string ime;
double GeografskaShirina;
double GeografskaDaljina;
double NadmorskaVisochina;
public:
city();
double getDaljina();
string getN();
void Output();
city(const city& p);
city& operator = (const city& p);
void quicksort(city bulgaria[], int left, int right);
;
city::city(const city& p)
ime = p.ime;
GeografskaDaljina = p.GeografskaDaljina;
GeografskaShirina = p.GeografskaShirina;
NadmorskaVisochina = p.NadmorskaVisochina;
city& city::operator = (const city& p)
if (this != &p)
ime = p.ime;
GeografskaDaljina = p.GeografskaDaljina;
GeografskaShirina = p.GeografskaShirina;
NadmorskaVisochina = p.NadmorskaVisochina;
return *this;
city::city()
cout << "Vavedete ime grad: ";
cin >> ime;
cout << "Vavedete geografskata shirina na grada: ";
cin >> GeografskaShirina;
cout << "geografskata daljina na grada: ";
cin >> GeografskaDaljina;
cout << "Vavedete nadmorska visochina na grada: ";
cin >> NadmorskaVisochina;
cout << "---------------------------------" << endl;
void city:: quicksort(city bulgaria[], int left, int right)
int min;
min = (left + right) / 2;
cout << left << endl;
cout << right << endl;
int i = left;
int j = right;
int pivot = bulgaria[min].getDaljina();
while (left < j || i < right)
while (bulgaria[i].getDaljina() < pivot)
i++;
while (bulgaria[i].getDaljina()>pivot)
j--;
if (i <= j)
city temp = bulgaria[i];
bulgaria[i] = bulgaria[j];
bulgaria[j] = temp;
i++;
j--;
else
if (left < j)
quicksort(bulgaria, left, j);
if (i < right)
quicksort(bulgaria, i, right);
return;
return;
double city::getDaljina()
return GeografskaDaljina;
string city::getN()
return ime;
void city::Output()
cout << "Imeto e " << ime << endl;
cout << "Geografskata shirina e " << GeografskaShirina << endl;
cout << "Geografskata duljina e " << GeografskaDaljina << endl;
cout << "Nadmorskata visochina e " << NadmorskaVisochina << endl;
int main()
int n;
int i=0;
cout << "Broi gradove : ";
cin >> n;
cout << endl;
city *bulgaria = new city[n];
bulgaria[i].quicksort(bulgaria, 0,n-1);
for (int i = 0; i < n; i++)
bulgaria[i].Output();
return 0;
【问题讨论】:
你来这里之前调试过你的代码吗? 【参考方案1】:您在 city::quicksort 的第二个 while 循环中使用了错误的索引。您可以使用 j 将正确的值与枢轴值进行比较:
while (bulgaria[j].getDaljina()>pivot)
j--;
【讨论】:
以上是关于快速排序的动态大量对象无法正常工作[关闭]的主要内容,如果未能解决你的问题,请参考以下文章