【问题标题】:How to quick sort characters/string input in C#?如何在 C# 中快速排序字符/字符串输入?
【发布时间】: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 翻译成所需的语言。

标签: c# sorting quicksort


【解决方案1】:

如果您查看Quicksort algorithm,您实际上并没有实现它。尝试这样的事情:

public class QuickSort : ISortStrategy
{

  public string Sort(string input)
  {
    if (string.IsNullOrEmpty(input)) return input;
    
    char[] chars = input.ToCharArray();
    this.Sort(chars, 0, unsorted.Length - 1);
    
    string output = new string(chars);
    return output;
  }
  
  private void Sort(char[] A, int lo, int hi)
  {
    if (lo >= 0 && hi >= 0 && lo < hi)
    {
      int p = partition(A, lo, hi);
      this.Sort(A, lo, p); // note: the pivot is now included
      this.Sort(A, p + 1, hi);
    }
    return;
  }
  
  private int partition(char[] A, int lo, int hi)
  {
    char pivot = A[ (lo+hi) / 2 ]; // integer division instead of floor(): we know that lo+hi is never negative.
    int i = lo - 1;
    int j = hi + 1;
    
    // loop forever
    while (true)
    {
      // Move the left index to the right at least once,
      // and while the element at the left index is less than the pivot.
      do
      {
        ++i;
      } while ( A[i] < pivot );
      
      // Move the right index to the left at least once,
      // and while the element at the right index is greater than the pivot
      do
      {
        ++j;
      } while ( A[j] > pivot );
      
      // if the indices converged (or crossed) return
      if (i >= j) return j;
      
      // swap A[i] and A[j]
      char temp = A[i];
      A[i] = A[j];
      A[j] = temp;
      
    }
    
  }
  
}

【讨论】:

  • 谢谢,但我有 IndexOutOfRangeException on: while (A[j] > pivot);调试显示 j=8 所以我将其更改为 while (A[j-2] > pivot);因为 A[] 只有 [0-6] 索引。但在下一次迭代后仍会变为 OutOfRange。我还将 unsorted.Length - 1 更改为 input.Length -1。
【解决方案2】:

它应该是

 if (low < j)
        {
            quickSort(low, i-1);
        }

【讨论】:

    猜你喜欢
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 2019-06-01
    • 1970-01-01
    相关资源
    最近更新 更多