gpt4 book ai didi

c++ - Shell排序和排序验证

转载 作者:行者123 更新时间:2023-11-28 05:23:27 25 4
gpt4 key购买 nike

我对编码相当陌生,我一直在努力研究这段代码,它允许我随机生成大量整数数组,选择特定的 shell 排序,然后测试数组是否排序正确。

#include <iostream>
#include <stdlib.h>
#include <time.h>
#define LISTLEN 100000
using namespace std;

void shellSort(int[], int, int[], int);
void testIfSorted(int[], int);

void main()
{
{
int list[LISTLEN];
int seq1[] = {LISTLEN/2};
int seq2[] = {2-1};
int seq3[] = { 4 + 3 * (2 ^ 0) + 1 };
int choice;

for (int i = 1; i < LISTLEN; i++)
{
list[i] = rand() % LISTLEN + 1;

cout << list[i] << endl;
}
cout << "\nEnter the Number for Which Sequence-Type You Wish to Use: \n"
"1) Shell Sequence\n"
"2) Hibbard Sequence\n"
"3) Sedgewick Sequence\n";
cin >> choice;

if (choice == 1)
{
shellSort(list, LISTLEN, seq1, LISTLEN / 2);
}
else if (choice == 2)
{
shellSort(list, LISTLEN, seq2, (2 - 1));
}
else if (choice == 3)
{
shellSort(list, LISTLEN, seq3, (4 + 3 * (2 ^ 0) + 1));
}

cout << "\nVerifying List was Sorted\n";
testIfSorted;
}
}

void shellSort(int arr[], int arrsize, int seq[], int seqsize)
{
clock_t t;
t = clock();
{
int j, temp;
for (int i = seqsize; i < arrsize; i += 1)
{
temp = seq[i];
for (j = i; j >= seqsize && seq[j - seqsize] > temp; j -= seqsize)
{
seq[j] = seq[j - seqsize];
}
seq[j] = temp;
cout << temp << endl << endl;
}
t = clock() - t;
printf("It took me %d clicks (%f seconds).\n", t, ((float)t) / CLOCKS_PER_SEC);
}
}

void testIfSorted(int list[], int length)
{
for (int i = 0; i < length - 1; i++)
{
if (list[i] < list[i + 1])
{
cout << "List Isn't Sorted Correctly\n";
}
else (list[i] > list[i + 1]);
{
cout << "List Sorted Correctly\n";
}
}
}

我不知道我做错了什么,shell 排序实际上并没有对数组进行排序,或者至少它没有进行降序排序,如果程序确实检查以确保数组已排序正确地,它不会显示我希望它显示的消息。

最佳答案

我没有具体的答案,但这些是一些快速调试技巧:

1 - 通过 clang-format 运行代码。如果您没有/不能在您的计算机上安装它,可以使用在线格式化程序,例如 http://format.krzaq.cc/

2 - 使用 clang 编译器编译您的代码,并打开所有警告。同样,如果您没有/不能在您的计算机上安装 clang,则可以使用一些在线沙箱。为什么是 clang ?他们付出了巨大的努力来提供非常好的警告/错误消息。

我都做了,这就是 clang 对程序的评价(链接 here)

prog.cc:10:1: error: 'main' must return 'int'
void main()
^~~~
int

prog.cc:41:9: warning: expression result unused [-Wunused-value]
testIfSorted;
^~~~~~~~~~~~

prog.cc:61:56: warning: format specifies type 'int' but the argument has type 'clock_t' (aka 'long') [-Wformat]
printf("It took me %d clicks (%f seconds).\n", t, ((float)t) / CLOCKS_PER_SEC);
~~ ^
%ld

prog.cc:45:20: warning: unused parameter 'arr' [-Wunused-parameter]
void shellSort(int arr[], int arrsize, int seq[], int seqsize)
^

prog.cc:72:22: warning: expression result unused [-Wunused-value]
(list[i] > list[i + 1]);
~~~~~~~ ^ ~~~~~~~~~~~

4 warnings and 1 error generated.

这些可能会有帮助 - 特别是最后一个!

关于c++ - Shell排序和排序验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41008980/

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