C++ C++;-实现快速排序的问题
所以我是递归新手,我试着实现一些算法,比如下面的快速排序,但它似乎工作得不太好。。。我认为问题在分区中,但我不确定问题可能是什么C++ C++;-实现快速排序的问题,c++,algorithm,sorting,recursion,quicksort,C++,Algorithm,Sorting,Recursion,Quicksort,所以我是递归新手,我试着实现一些算法,比如下面的快速排序,但它似乎工作得不太好。。。我认为问题在分区中,但我不确定问题可能是什么 #include <iostream> using namespace std; const int MAX = 100; typedef int matrix[MAX]; struct Taula{ matrix m; int n; }; void wwap(Taula &t, int n, int i, int posP
#include <iostream>
using namespace std;
const int MAX = 100;
typedef int matrix[MAX];
struct Taula{
matrix m;
int n;
};
void wwap(Taula &t, int n, int i, int posPivot)
{
int aux = t.m[posPivot];
t.m[posPivot] = t.m[i];
t.m[i] = aux;
}
void partition(Taula &t, int n, int left, int right, int &posPivot)
{
int pivot = t.m[right];
posPivot = left;
for (int i = left; i < right-1; i++){
if (t.m[i] < pivot){
swap(t,n,i,posPivot);
posPivot = posPivot+1;
}
}
swap(t,n,posPivot,right);
}
void quicksort(Taula &t, int n, int left, int right)
{
int k;
if (left < right){
particio(t,t.n,left,right,k);
quicksort(t,t.n,left,k-1);
quicksort(t,t.n,k+1,right);
}
}
int main()
{
Taula t;
t.n = 0;
cout << "INTEGER SEQUENCE ENDED WITH -2:" << endl;
int x; cin >> x;
while (x != -2){
t.m[t.n] = x;
t.n++;
cin >> x;
}
cout << t.n << " ELEMENTS" << endl;
quicksort(t,t.n,0,t.n);
cout << "SORT:" << endl;
for (int i = 0; i < t.n; i++) cout << t.m[i] << endl;
return 0;
}
谢谢你的帮助 你必须从左开始,直到找到比你的轴更大的数字,然后从右到左开始,直到找到一个更低的数字。。。(这两个循环使快速排序非常快…)看看这段代码 这两行都需要:
while Array[L2] < PivotValue do // scan left partition
L2 := L2 + 1;
while Array[R2] > PivotValue do // scan right partition
R2 := R2 - 1;
而数组[L2]PivotValue不//扫描右分区
R2:=R2-1;
这就是你的问题:
for (int i = left; i < right-1; i++){
if (t.m[i] < pivot){
swap(t,n,i,posPivot);
posPivot = posPivot+1;
}
}
for(int i=left;i
你必须从左开始,直到找到比你的轴心更大的数字,然后从右到左开始,直到找到一个更低的数字。。。(这两个循环使快速排序非常快…)看看这段代码
这两行都需要:
while Array[L2] < PivotValue do // scan left partition
L2 := L2 + 1;
while Array[R2] > PivotValue do // scan right partition
R2 := R2 - 1;
而数组[L2]PivotValue不//扫描右分区
R2:=R2-1;
这就是你的问题:
for (int i = left; i < right-1; i++){
if (t.m[i] < pivot){
swap(t,n,i,posPivot);
posPivot = posPivot+1;
}
}
for(int i=left;i
您正在使用Lomuto分区方法。正确的方法:
for (int i = left; i <= right-1; i++){
if (t.m[i] <= pivot){
swap(t,n,i,posPivot);
posPivot = posPivot+1;
}
您正在使用Lomuto分区方法。正确的方法:
for (int i = left; i <= right-1; i++){
if (t.m[i] <= pivot){
swap(t,n,i,posPivot);
posPivot = posPivot+1;
}
分词??你是说分割吗?分割??你是说分区吗?当L2大于R2时,而不是当left>right-1Thomas时,你必须停止,谢谢你的回答,我已经用@MBo帮助修复了它。。。尽管你帮我理解了算法,谢谢!当L2大于R2时,而不是当left>right-1Thomas时,您必须停止,谢谢您的回答,我已经用@MBo帮助修复了它。。。尽管你帮我理解了算法,谢谢!非常感谢你。。。我认为t-n-1基本上是不需要的,因为我一直在做for循环,直到我