QuickSort does not work

I'm just trying to implement Quicksort line by line, but it does not work. An output exits in the same way as an input, not a sorted string. I checked many times, but can not find the error. Please help me.

The following is a quick sort function.

void quicksort(string str1, int si, int ei)
{
    if (si < ei)
    {
        int pi = partition(str1, si, ei);
        quicksort(str1, si, pi-1);
        quicksort(str1, pi+1, ei);
    }
}

Section function.

int partition(string str2, int si, int ei)
{
    int i = si-1;
    char x = str2[ei];
    int j;
    for (j = si ; j <= ei-1 ; j++)
    {
        if (str2[j] <= x)
        {
            i++;
            exchange(&str2[i], &str2[j]);
        }
    }
    exchange(&str2[ei], &str2[i+1]);
    return i+1;
}

and sharing functions.

void exchange(char *a, char *b)
{
    char temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

The main function is given below.

int main()
{
    int l1;
    string str;
    cout << "Enter the string to be sorted";
    cin >> str;
    l1 = str.length();
    quicksort(str, 0, l1-1);
    cout << str;
    return 0;
}
+4
source share
1 answer

quicksorttakes value str1by value, and then recursively copies it into its subtasks. Each instance runs on a separate, unrelated line and makes changes to its local copy.

You need to pass strthe link:

void quicksort(string& str1, int si, int ei)

And the same for partition:

int partition(string& str2, int si, int ei)
+5

Source: https://habr.com/ru/post/1606842/


All Articles