0

I have one array containing chars from the input and the other array containing pointers to the corresponding chars in the first array. This part went good.

But then I would like to bubble sort the char** array (array of pointers) so the original array stays untouched but something goes wrong(the text is not sorted).

EDIT: Please discuss only the sorting algorithm


 char tab[200];//array of chars 
 char** t = new char*[tabLength];
 //SOMETHING
....

....
int n = tabLength;//length of tab(length of the word it contains)
//TILL HERE EVERYTHING IS FINE -----------------------------------
         //bubble sorting below
do{
    for(int i = 0; i < n -1; i++){
        if(*t[i] > *t[i+1]){
            char* x = t[i];
            t[i] = t[i+1];
            t[i+1] = x;
        }
        n--;
    }
}while(n>1);

cout<<"sorted input";
for(int i = 0; i < tabLength; i++)
    cout<<t[i];
    cout<<endl;

cout<<"original"<<tab<<endl;
4
  • Is each entry meant to be a C string, or a single char? Commented Mar 16, 2013 at 17:35
  • Why do you calculate the length yourself? Why do you even use C-style string instead of std::string? If you did use std::string, then you could just copy the string and then use std::sort to sort it. Commented Mar 16, 2013 at 17:35
  • @NPE I think he's trying to sort the letters in a C-style string. But instead of actually modifying the array, he's reordering pointers into that array. Commented Mar 16, 2013 at 17:37
  • @sftrabbit YES, exacly. Commented Mar 16, 2013 at 18:11

2 Answers 2

1

Make sure you print out the values that the pointers point at:

for(int i = 0; i < tabLength; i++)
  cout << *t[i];
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Could you look at the edit I cut off the code so there is only the sorting algorithm visible. I would like to sort only t array (sort pointers).
0

I would simply use the functionality already at my disposal in the standard library:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    std::string original;
    std::getline(std::cin, original);

    std::cout << '|' << original << "|\n";

    std::string sorted = original;
    std::sort(std::begin(sorted), std::end(sorted));

    std::cout << "Sorted  : " << sorted << '\n';
    std::cout << "Original: " << original << '\n';
}

Test run:

|Hello world, how are you doing today?|
Sorted  :       ,?Haadddeeghilllnoooooorrtuwwyy
Original: Hello world, how are you doing today?

1 Comment

Because I try to understand how to sort array of pointers to other array elements(chars not strings).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.