-2

I am new in C++. And for my first ever problem about Quick Sort algorithm, when I run the code, it wont stop asking for input. Even though i have been running the code from a different IDE the problem persists.

#include <bits/stdc++.h>
#include <iostream>
using namespace std;
void swap(int &x, int &y){
int temp; 
temp=x;
x=y;
y=temp;
}
void part(int *a, int lo, int hi){
if(lo<hi){
int p=lo;
int s=lo;
int e=hi;
while(s<e){
    while(a[s]<=a[p]){
        if(s!=hi+1){
        s++;
        }else{
            s--;
        }
    }
    cout<<s<<endl;
    while(a[e]>a[p]){
        e--;
    }
    cout<<e<<endl;
    while(s<e){
    swap(a[s], a[e]);
    cout<<a[s]<<a[e];
    }
}
swap(a[p], a[e]);

part(a, lo, e-1);
part(a, e+1, hi);
}
}
int main(){
int n;
cin>>n;
int *arr=new int[n];
for(int i=0; i<n; i++){
    cin>>arr[i];
}"it wont go after this"
part(arr, 0, n-1);
for(int i=0; i<n; i++){
    cout<<arr[i]<<" ";
}
return 0;
}

I am unable to get the answer. Hope you guys will help me out. Thanks in advance

  • Can you also add what input you are giving to the program ? – Deepak Patankar Sep 13 '20 at 11:21
  • Try printing the value of `n`, before the first for loop, maybe your input is incorrect and it ends up as a giant number. – Maciej Dziuban Sep 13 '20 at 11:24
  • If you are just starting to learn, then do yourself a favour and learn from these two questions: [Why should I not #include ?](https://stackoverflow.com/q/31816095/5910058) and [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/5910058). Don't ever do the first, rarely consider the second and *never ever* do both at the same time. – Jesper Juhl Sep 13 '20 at 11:30
  • Hey @Shubham Bansode, I have pointed out one infinite loop case in the code. Can you try fixing this case? – Deepak Patankar Sep 13 '20 at 11:43
  • `int *arr = new int[n];` isn't really valid C++ code. I believe MSVC and possibly some other compilers will allow that, but if you need a container whose size isn't known at compile time you probably want an `std::vector`. – Nathan Pierson Sep 13 '20 at 14:40

1 Answers1

0

The code is not stuck at the input rather it encounters an infinite loop, to check the same you can print a cout and check if the statement is printed or not.

cout<<" Read the array elements"<<endl;
part(arr, 0, n-1);

One case in which infinite loop occurs is in lines

    while(a[s]<=a[p]){
        if(s!=hi+1){
        s++;
        }else{
            s--;
        }
    }

Assume the following case:

  1. The value of s reaches hi + 1, then
  2. We decrement the value of s, then s becomes hi
  3. Next since the value of s != hi + 1, you increment the value of s and now it equals hi + 1. We are back to point 1.
Deepak Patankar
  • 3,076
  • 3
  • 16
  • 35