What is wrong with my implementation of quicksort? [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
The program below is for sorting a list using quicksort C++.The code typed below has compiled successfully in code::blocks and in http://cpp.sh/, but unfortunately it hangs after entering in the elements,any help will be appreciated..
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);
}

Passing by reference is must as others have pointed out.
Keep pivot constant during a partition. pivot = v[pivot] ensures that.
outer loop bounds changed to left<=right from left<right.
The running code.
#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;
}

Related

Program is running but the expected output is not showing [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last year.
Improve this question
#include<conio.h>
#include<stdio.h>
#include<iostream>
using namespace std;
class binary_search
{
public:
int a[10],flag;
int n,i,j,index,num,temp,mid,low,high;
void getdata();
void search();
void sort_array();
};
void binary_search::sort_array()
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[j]>a[j+1])
{
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
}
void binary_search::getdata()
{
cout<<"number of array "<<"\n";
cin>>n;
cout<<"\nEnter array : "<<"\n";
for(i=0;i<n;i++)
{
cin>>a[i];
}
sort_array();
cout<<"\nSorted Array Elements: ";
for(i=0;i<n;i++)
{
cout<<a[i];
}
}
void binary_search::search()
{
cout<<"\nEnter value to search: ";
cin>>num;
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==num)
{
cout<<"\nNumber is found at position "<<mid;
break;
}
else if(a[mid]>num)
{
high=mid-1;
}
else if(a[mid]<num)
{
low=mid +1;
}
else if(a[mid]!=num)
{
flag=false;
}
}
if(!flag)
{
cout<<"\nNumber is not found!!!";
}
}
int main()
{
binary_search b;
b.getdata();
b.search();
getch();
return 0;
}
Program is running but the expected output is not showing.
I'm not getting the message of "not found the number". I think I am missing something if any guidance I will get it will be awesome. Someone refer me to remove conion.h and getch() ; but still the output is not showing as expected.
Actually it's a code for binary search in C++
You must be facing problem in the test cases where, number of elements in array is exactly equal to 10. Because, if you look closely, the sort_array() that you have made have some logical error.
This is your sort_array() function which is using bubble sort technique.
void binary_search::sort_array()
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[j]>a[j+1])
{
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
}
But, consider the case if n = 10, at this point int the inner loop code will try to access a[10], which is not present. So, it will go out of bound which will lead to undesirable results. So, try changing your function to the one below.
void binary_search::sort_array()
{
for(int i=0;i<n - 1;i++)
{
for(int j=0;j<n - i - 1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
}
}
}
Apart from this remove #include<conio.h> and getch()

wrong output on printing subsets of array [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am trying to print all the subsets of an array. But not getting the correct output.
#include<iostream>
using namespace std;
int arr[]={1,2,3,4,5};
int n=5;
void print(int a[],int cnt, int idx)
{
if(idx==n)
{
for(int i=0;i<cnt;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
return;
}
a[cnt]=arr[idx];
print(a,cnt,idx+1);
print(a,cnt+1,idx+1);
}
int main()
{
int a[5]={0};
print(a,0,0);
}
the above code only prints "5"
Please help me to rectify the same.
Replace the array with a vector. As the array in C++ is passed by reference, the print function is accessing the same array, which causes the problem.
#include <iostream>
#include<vector>
using namespace std;
int arr[]={1,2,3,4,5};
int n=5;
void print(vector<int>a,int cnt, int idx)
{
if(idx==n)
{
for(int i=0;i<cnt;i++)
{
cout<<a[i]<<" ";
}
cout<<endl;
return;
}
a[cnt]=arr[idx];
print(a,cnt,idx+1);
print(a,cnt+1,idx+1);
}
int main()
{
vector<int >a(5,0);
print(a,0,0);
}

Postfix notation stack C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am new to C++ and I want to use a stack to evaluate an expression given as an input (2+3*5+4 for example), containing only numbers, + and *. I wrote this code but it gives me Segmentation fault: 11. Could you please help me solve this or give me a hint about what could be wrong? Thank you! (I noticed there were similar questions on this site, but I couldn't use them to solve my problem)
#include <iostream>
#include <stack>
using namespace std;
bool highPrecedence(char a, char b){
if((a=='+')&&(b=='*'))
return true;
return false;
}
int main()
{
char c = 'a';
double x;
stack<char> stack;
double v[10];
int i=0;
double res;
while(true)
{
c = cin.get();
if(c=='\n'){
while(stack.size()!=0){
if (stack.top()=='*'){
double res = v[i]*v[i-1];
i--;
v[i]=res;
stack.pop();
}
if (stack.top()=='+'){
res = v[i]+v[i-1];
i--;
v[i]=res;
stack.pop();
}
}
break;
}
if ( '0'<=c && c<='9' )
{
cin.putback(c);
cin>>x;
cout<<"Operand "<<x<<endl;
i=i+1;
v[i]=x;
}
else
{
if(c!=' ') cout<< "Operator " <<c<<endl;
if (stack.size()==0)
stack.push(c);
else{
while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
if (stack.top()=='*'){
double res = v[i]*v[i-1];
i--;
v[i]=res;
stack.pop();
}
if (stack.top()=='+'){
res = v[i]+v[i-1];
i--;
v[i]=res;
stack.pop();
}
}
stack.push(c);
}
}
}
cout<<v[0]<<endl;
}
Using stack.top() is illegal if the stack is empty.
Change while((!highPrecedence(stack.top(),c)) && (stack.size()!=0)){
to while((!stack.empty()) && (!highPrecedence(stack.top(),c))){
The initiali value of i is not good and you are printing uninitialized variable, which has indeterminate value.
Change int i=0; to int i=-1;

Generating permutation of string without duplicates [duplicate]

This question already has answers here:
Finding all the unique permutations of a string without generating duplicates
(5 answers)
Closed 9 years ago.
I have writing a general program to generate permutation of string but removing the duplicate cases . For this I am using memorization by using .
void permute(char *a,int i, int n,set<char*> s)
{
if(i==n)
{
if(s.find(a)==s.end()){
cout<<"no dublicate"<<endl;
cout<<a<<endl;
s.insert(a)
}
}
else{
for(int j=i;j<n;j++)
{
swap(a[i],a[j]);
permute(a,i+1,n,s);
swap(a[i],a[j]);
}
}
}
int main()
{
char a[]="aba";
set <char*> s;
permute(a,0,3,s);
return 0;
}
But the result is not as desired. It prints all the permutation. Can anyone help me in figuring out the problem.
First, you pass set<> s parameter by value, which discards your each insert, because it's done in the local copy of s only. However even if you change it to pass by reference, it won't work, because every time you insert the same char* value, so only one insert will be done. To make your code work correctly I suggest to change the prototype of your function to
void permute(string a,int i, int n,set<string>& s)
and this works all right.
update: source code with described minor changes
void permute(string a,int i, int n,set<string>& s)
{
if(i==n)
{
if(s.find(a)==s.end()){
cout<<"no dublicate"<<endl;
cout<<a<<endl;
s.insert(a);
}
}
else{
for(int j=i;j<n;j++)
{
swap(a[i],a[j]);
permute(a,i+1,n,s);
swap(a[i],a[j]);
}
}
}
int main()
{
string a ="aba";
set <string> s;
permute(a,0,3,s);
return 0;
}

Two questions of c++ which just change a little,however very different answers

Recently I do a exercise about algorithm with c++. Exercise in here:poj
I find two very confused questions.
I write a class MAZE and there are three primary functions in MAZE,they are
int left_path();int right_path();int mini_path();
and a function to print the answers:
void display(){
cout<<left_path()<<" "<<right_path()<<" ";
cout<<mini_path()<<endl;
}
the program can work correctly.As we see the function display() can be easy;
I write like this
void display(){
cout<<left_path()<<" "<<right_path()<<" "<<mini_path()<<endl;
}
just one change ;however the program can't work,it like loop infinitely.
following is the other question:
the function mini_path's frame like this
int maze::mini_path(){
ini();
queue<pair<int,int> > q;
q.push(make_pair(x,y));
while(!q.empty()){
pair<int,int> tmp=q.front();
q.pop();
int t=...;
if(E){
return t;
}
if(E){
S
}
if(E){
S
}
if(E){
S
}
if(E){
S
}
}
return -1;
}
if there is "return -1" in the end ,the function works right,else the function return random big number.
The program is in only one file and i use the gun compiler.
I don't show the total codes,because i think nobody wants to see them.I just want to ask what problems may lead above strange behaviors.
source code(simplified for question2):
typedef enum {LEFT=-1,RIGHT=1,UP,DOWN} direction;
ifstream fin("file_test3.txt");
class maze{
public:
maze(){input();}
int mini_path();
void input();
void display(){
cout<<mini_path()<<endl;
}
private:
bool is_not_dest(){
return !(x==d_x && y==d_y);
}
void ini_dir()
{
if(e_x==0) dir=DOWN;
else if(e_x==height-1) dir=UP;
else if(e_y==0) dir=RIGHT;
else dir=LEFT;
}
void ini(){
x=e_x;
y=e_y;
path_lenth=1;
ini_dir();
}
direction dir,d;
int width,height,maze_map[40][40],path_lenth;
int x,y,e_x,e_y,d_x,d_y;
};
void maze::input()
{
fin>>width>>height;
char sym;
for(int i=0;i<height;++i)
for(int j=0;j<width;++j){
fin>>sym;
if(sym=='#')
maze_map[i][j]=1;
else if(sym=='.')
maze_map[i][j]=0;
else if(sym=='S'){
maze_map[i][j]=-1;
e_x=i;
e_y=j;
}
else {
maze_map[i][j]=-2;
d_x=i;
d_y=j;
}
}
}
int maze::mini_path()
{
ini();
queue<pair<int,int> > q;
if(dir==LEFT) {maze_map[x][--y]=2;}
else if(dir==RIGHT) {maze_map[x][++y]=2;}
else if(dir==UP) {maze_map[--x][y]=2;}
else {maze_map[++x][y]=2;}
q.push(make_pair(x,y));
while(!q.empty()){
pair<int,int> tmp=q.front();
q.pop();
x=tmp.first;
y=tmp.second;
int t=maze_map[x][y]+1;
if((x==d_x && (y-d_y==1 || y-d_y==-1)) ||(y==d_y && (x-d_x==1||x-d_x==-1))){
return t;
}
if(maze_map[x-1][y]==0){
maze_map[x-1][y]=t;
q.push(make_pair(x-1,y));
}
if(maze_map[x+1][y]==0){
maze_map[x+1][y]=t;
q.push(make_pair(x+1,y));
}
if(maze_map[x][y-1]==0){
maze_map[x][y-1]=t;
q.push(make_pair(x,y-1));
}
if(maze_map[x][y+1]==0){
maze_map[x][y+1]=t;
q.push(make_pair(x,y+1));
}
}
return -1;
}
main()
{
int n;
fin>>n;
while(n-- >0){
class maze m;
m.display();
}
}
I see it! Can you see it? :)
#include <iostream>
using namespace std;
int foo(int bar)
{
cout << bar << endl;
return bar;
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << foo(1) << foo(2) << foo(3) << endl;
return 0;
}
The output:
3
2
1
123
regarding question1:
The order in which the functions are called will be different.
the first solution will call them in following order:
right_path
left_path
mini_path
the second solution results in following order:
mini_path
right_path
left_path
so the solution you probaly want is:
void display(){
cout<<left_path()<<" ";
cout<<right_path()<<" ";
cout<<mini_path()<<endl;
}
There is not enough info to answer the first question; both codes are equivalent.
[Edit:Check other answers. Anyway, both codes should be equivalent: you have bugs in your code.]
About the second question, I guess that that "return -1" marks "no possible path" in your maze, that's why, when you remove it, your program stops working.
In the maze problem, a backtracking algorithm moves square by square. When from a square there is no possible path, this square must be marked as no path.