gpt4 book ai didi

C++ 快速排序字母数组

转载 作者:行者123 更新时间:2023-11-28 03:20:34 24 4
gpt4 key购买 nike

我正在尝试使用快速排序对字母表数组进行排序。

我基本上尝试从主要算法出发并将其转换为使用 char 数组。

我想我快到了,但我似乎做不到。

非常感谢任何帮助。

:)

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

int qscounter = 0;

int split(char a[], char low, char high)
{
char part_element = a[low];

for (;;) {
while (low < high && part_element <= a[high])
high--;
if (low >= high) break;
a[low++] = a[high]; 
while (low < high && a[low] <= part_element)
low++;
if (low >= high) break;
a[high--] = a[low];
}
a[high] = part_element;
return high;
}

void quick_sort(char a[], char low, char high)
{
char middle;

if (low >= high) return;
middle = split(a, low, high);
qscounter++;
quick_sort(a, low, middle - 1);
quick_sort(a, middle + 1, high);

printf("Quick Sort: %d\n", qscounter);
for(int i=0;i<26;i++)
printf("%c",a[i]);
printf("\n\n");
}

void main()
{
char unsorted_alphabet[26] = {'A','E','O','D','B','Q','G','V','Y','J','Z','S','M','N','C','P','F','R','L','T','U','H','W','X','I','K'};
quick_sort(unsorted_alphabet,unsorted_alphabet[0],unsorted_alphabet[25]);
fflush(stdin);
getchar();
}

最佳答案

您的代码存在以下问题: 您试图将元素值用作数组索引,这肯定是错误的。您将 a[0] 和 a[25] 作为索引传递给 quick_sort 函数,但是,low 和 high 应该是整数类型,而不是 char。您不能使用 char 值作为索引,因为数组值最初是乱序的,而数组索引则不是。

正确的代码应该是这样的:

int split(char a[], int low, int high) //should be integer type for low and high
{
char part_element = a[low];
//if low is a char, what is a[char]? It will not be the value you intended to want

//do same thing in your code
}

void quick_sort(char a[], int low, int high)
{
int middle; //not char

//do same thing as in your code

在 main() 中,函数调用应该是:

 quick_sort(unsorted_alphabet,0,25); //should pass array indices

经过这些小改动后它实际上工作正常:我得到了:

Quick Sort: 20
ABCDEFGHIJKLMNOPQRSTUVWXYZ

关于C++ 快速排序字母数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15561170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com