You are here:



Hi, I'm having a little trouble understanding this program (contains recursion codes), can you help explain?

#include <iostream>
#include <cstring>
using namespace std;

void quicksort (char *items, int len);
void qs (char *items, int left, int right);

int main() {
  char str[] = "kjhjgdgutsgnbnbwtraf";
  cout << "Original order: " << str << "\n";

  quicksort(str, strlen(str));

  cout << "Sorted order: " << str << "\n";

  return 0; }

void quicksort (char *items, int len) { qs(items, 0, len-1); }

void qs (char *items, int left, int right) {
  int i, j;
  char x, y;


  do {
     while ((items[i] < x) && (i< right)) i++;
     while ((x < items[j]) && (j > left)) j--;

     if(i <= j) {
        y = items [i];
        items [i] = items [j];
        items [j] = y;
        j--; }
  while (i <= j);

  if (left < j) qs (items, left, j);
  if (i < right) qs (items, i, right); }

I've only learned how to control strings when they are already in the program, can you show me how to interact with the user with string? (The user enters the string, and the program manipulates it.)

Additionally, here is another part of program that I don't understand:
void reverse(char *s) {
if (*s) reverse (s+1);
else return; }

cout << *s; }

What does (*s) do?


To enter strings for the program to process use cin.

I do not think you have the entire recursive program because the brackets are not properly pared.  From what I see, all the recursive program does is checks if the current character is the null character. If it is not it recursively checks the next character.  If it is it returns.

From the code in the unpaired bracket, it looks like the recursive routine should print one character at a time after the null character is found as it returns recursively each time which will print the string in reverse sequence.


All Answers

Answers by Expert:

Ask Experts


Titus B. Ledbetter, Jr.


C , MFC, Object Oriented, Artificial Intelligence


I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Master's Degree Computer Science from Johns Hopkins

©2017 All rights reserved.

[an error occurred while processing this directive]