c++ - 通过交换指针对 char 数组进行排序,C++

标签 c++ c arrays sorting

我正在尝试通过交换指针对 char 指针数组 (char * _string) 进行排序。

我有这个方法,我想做的是使用从 _string 获得的值,并通过不操作 _string 来对它们进行排序,而是通过空辅助数组(char * _output)将其移交给该方法。

谁能帮助我并告诉我我做错了什么?

void sortAsc(char* _string, char* _output) 
{

    int length = strlen(_string);

        // output and string now point to the same area in the memory
    _output = _string; 

    for( int i = 0; i < length; i++) {
          for( int j = 0; j < length; j++) {
                if( *(_output) > (_output[j] ) ) {

                    // save the pointer
                    char* tmp = _output;

                    // now output points to the smaller value   
                    _output = _output+j; 

                    // move up the pointer to the smaller value
                    _output + j; 

                    // now the pointer of the smaller value points to the higher value
                    _output = tmp; 

                    // move down to where we were + 1
                    _output - j + 1; 

            }
        }
    }

    //_output[length]='\0';

    //delete chars;
 }

在我的 main-Method 中,我做了这样的事情:

char * string = {"bcdae"};
char * output = new char[5];
sortAsc(string, output);

在该代码之后,我希望输出数组包含排序后的值。

最佳答案

让我们使用指针表示法对 10 大小的 int 数组进行选择排序,您只需将其更改为数组列表即可。

      *---*---*---*---*---* ........
a[] = | 1 | 2 | 4 | 0 | 3 | ........
      *---*---*---*---*---* ........
        ^--------We start here looking for the smaller numbers and sort the array.


for( i = 0; i < 10; i++ ){
    k = i;
    bypass = *( a + i );
    for( j = i + 1; j < 10; j++ ){

        /* To get Increasing order. */
        if( bypass > *( a + j ) ){
           bypass = *( a + j );
           k = j;
        }
    }
    if ( k != i ){
         *( a + k ) = *( a + i );
         *( a + i ) = bypass;
    }
}

关于c++ - 通过交换指针对 char 数组进行排序,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13520530/

相关文章:

c# - 在代码隐藏中将模型数组绑定(bind)到 View 模型

c++ - 类实例化的枚举数而不是构造函数?

c - fscanf 仅获取十六进制数的前 4 个字节

c - 如何在Linux中串行写入数据到USB端口

c - “Fun with Rotation” - Codechef 九月长期挑战赛

javascript - 具有单个元素的 RegisterArrayDeclaration

c++ - 为什么这个 C++ 递归模板不起作用?

c++ - 使用 Crypto++ 的 AES 实现

c++ - 使用 CodeBlocks 将 GLEW 链接到 SFML 项目时出现问题

java - 这是将 String hex 转换为字节的最佳方法吗?