下面的程序是使用quicksort C ++对列表进行排序。下面输入的代码已经在code :: blocks和http://cpp.sh/中成功编译,但不幸的是它在输入元素后挂起,任何帮助都将受到赞赏..
void quicksort(vector<int> v,int left_index,int right_index)
{
if(left_index>=right_index)
return;
int pivot=(right_index+left_index)/2;
int left=left_index;
int right=right_index;
while(left<=right)
{
while(v[left]<v[pivot])
left++;
while(v[right]>v[pivot])
right--;
if(left<=right)
{
swap(v,left,right);
left++;right--;
}
}
quicksort(v,left_index,right);
quicksort(v,left,right_index);
}
答案 0 :(得分:1)
pivot = v[pivot]
确保了这一点。 left<=right
更改为left<right
。正在运行的代码。
#include <iostream>
#include<vector>
using namespace std;
void print(const vector<int> &v)
{
cout<<"The sorted list is:"<<endl;
for(int i=0;i<(int)v.size();i++)
cout<<v[i]<<' ';
cout<<endl;
}
void swap(vector<int> &v,int left,int right)
{
int temp=v[left];
v[left]=v[right];
v[right]=temp;
}
void quicksort(vector<int> &v,int left_index,int right_index)
{
if(left_index>=right_index)
return;
int pivot=(right_index+left_index)/2;
pivot = v[pivot];
int left=left_index;
int right=right_index;
while(left<right)
{
while(v[left]<=pivot)
left++;
while(v[right]>pivot)
right--;
if(left<right){
swap(v,left,right);
left++;
right--;
}
}
quicksort(v,left_index,right);
quicksort(v,left,right_index);
print(v);
}
int main()
{
int no;
vector<int> v;
cout << "Please enter the elements in your list" << endl;
cout << "Enter 0 to exit..."<<endl;
while(cin >> no)
{
if(no==0)
break;
v.push_back(no);
}
quicksort(v,0,v.size()-1);
return 0;
}