Hi there everyone. I wonder if you could help me with my code. It just seems to go into an infinite loop. I would greatly appreciate some help with this. Thanks

#include<iostream>
using namespace std;

int qsrt(int array[], int first, int last)

{
    

    int over = 0;
    over = first-last;
    int g=0;

    if(over==0)
    {
    return 0;
    }
    
    int c=0;
    
    int start = first;
    int end = last;
    int pivot = array[first];
    int temp =0;
    
     while(first != last)
     {

    while((array[last]>pivot)&&(first != last))
    {
        last--;
    }

    while((array[first]<pivot)&&(first != last))
    {
        first++;
    }
    
    temp = array[last];
    array[last] = array[first];
    array[first] = temp;

     

    c = last-first;

     if(c>1)
     {
         first++;
         last--;
     }
     
 }
     
      c= 0;
     c= first-1;
     
     qsrt(array,first,end);
     qsrt(array,start,(c));

   return 0;
}

int main (void)

{
    int anarray[9] = {4,5,3,8,5,6,2,8,9};
    
    
    
    qsrt(anarray,0,8);
    system("pause");
    

    return 0;
}

Thanks once again

Recommended Answers

All 2 Replies

IF your intent is to sort a range of integers beginning at first and continuing to last, there are simpler ways to do it.
You don't need two loops or so many extra varaibles.

If you need to sort from both ends, shouldn't pivot be in the middle of the arrary rather than equal to array[first]?

#include<iostream>
using namespace std;

int qsrt(int array[], int first, int last){ 
    int over = 0;
    over = first-last;
    int g=0;
    if(over==0){
        return 0;
    }int c=0;
    int start = first;
    int end = last;
    int pivot = array[first];
    int temp =0;
    while(first != last){
        while((array[last]>pivot)&&(first != last)){
            last--;
        }while((array[first]<pivot)&&(first != last)){
            first++;
        }temp = array[last];
        array[last] = array[first];
        array[first] = temp;
        c = last-first;
        if(c>1){
            first++;
            last--;
        }
    }c= 0;
    c= first-1;
    qsrt(array,first,end);
    qsrt(array,start,(c));
    return 0;
}

int main (void){
    int anarray[9] = {4,5,3,8,5,6,2,8,9};
    qsrt(anarray,0,8);
    system("pause");
    return 0;
}

first, you should learn how to format your code correctly...


second, saying this

int a=0;
a=b-c;

is the same thing as saying

int a=b-c;

when you have b and c declared...

third, what are you doing there? it seems like you are ordering numbers from least to greatest... but... JRM is right... you could do this with less variables...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.