【发布时间】:2022-08-09 12:23:41
【问题描述】:
我的任务是实现不同的排序算法:快速排序和合并排序。
我设法获得快速排序,但我注意到它给了我一个不同的答案。例如,冒泡排序会将 \"program\" 排序为 \"agmoprr\",但我的快速排序会将其排序为 \"agomprr\"。冒泡排序已经给出,所以我想我错过了快速排序的一些东西。
有人可以帮我检查我哪里出错了吗?谢谢
public class QuickSort : ISortStrategy
{
char[] myArray;
public string Sort(string input)
{
if (input == null || input.Length == 0 || input.Length == 1)
{
return null;
}
int length = input.Length;
int low = 0, high = length - 1;
this.myArray = input.ToCharArray();
quickSort(low, high);
return new string(myArray);
}
public void quickSort(int low, int high)
{
int i = low;
int j = high;
char tmp;
int pivot = (low + high) / 2;
while (i <= j)
{
while (myArray[i] < myArray[pivot])
{
i++;
}
while (myArray[j] > myArray[pivot])
{
j--;
}
if (i <= j)
{
tmp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = tmp;
i++;
j--;
}
}
if (low < j)
{
quickSort(low, j);
}
if (i < high)
{
quickSort(i, high);
}
}
}
界面
public interface ISortStrategy
{
string Sort(string input);
}
主班
using System;
/**
* Instructions:
* Use the Strategy Pattern to implement the different Sorting Algorithms: BubbleSort (given as an example), Quick Sort and Merge Sort
*/
class Program
{
static void Main(string[] args)
{
Console.WriteLine(\"Enter Sort Strategy (bubblesort, quicksort, mergesort). Defaults to bubblesort\");
ISortStrategy strategy = default;
var input = Console.ReadLine();
input = input.ToLower();
if (input == \"bubblesort\")
{
strategy = new BubbleSort();
}
// Implement other strategies here based on the strategy inputted by the user
if (input == \"quicksort\")
{
strategy = new QuickSort();
}
if (input == \"mergesort\")
{
strategy = new MergeSort();
}
Console.WriteLine(\"Enter String to Sort\");
var value = Console.ReadLine();
Console.Write(\"The sorted string is: \" + strategy.Sort(value));
Console.ReadKey();
}
}
-
你知道如何调试代码吗?目前感觉你只是在猜测你的代码是如何工作的。您应该尝试调试它并检查发生的事情是否与您的期望相反。 quickSort 方法中的两个内部 while 循环是调试会话的一个很好的起点。如果您正在查看的值等于枢轴值,会发生什么?
-
谢谢,实际上我之前没有尝试过调试代码,因为我们很少使用算法,而且大部分已经在 java 中给出。我通常将算法从 java 翻译成所需的语言。