I have a hw on using strategy design patterns for the different sorting algorithms. The bubble sort has already been done but I get an error in my Quick Sort Algorithm
**The error code is: CS0161 'QuickSort.Sort(string)': not all code paths return a value**
for the main menu
namespace Yousource.Strategy.App
{
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();
switch (input)
{
case "bubblesort":
strategy = new BubbleSort();
break;
case "mergesort":
strategy = new MergeSort();
break;
case "quicksort":
strategy = new QuickSort();
break;
default:
strategy = new BubbleSort();
break;
}
Console.WriteLine("Enter String to Sort");
var value = Console.ReadLine();
Console.Write("The sorted string is: " strategy.Sort(value));
Console.ReadKey();
}
}
}
for the Strategy Pattern
namespace Yousource.Strategy.App
{
public interface ISortStrategy
{
string Sort(string input);
}
}
for the Quick Sort process
namespace Yousource.Strategy.App
{
public class QuickSort : ISortStrategy
{
public string Sort(string input)
{
var result = "";
var arr = input.ToCharArray();
char temp;
for (int write = 0; write < arr.Length; write )
{
for (int sort = 0; sort < arr.Length - 1; sort )
{
if (arr[sort] > arr[sort 1])
{
temp = arr[sort 1];
arr[sort 1] = arr[sort];
arr[sort] = temp;
}
}
}
for (int i = 0; i < arr.Length; i )
result = arr[i];
return result;
}
}
}
CodePudding user response:
Confused compiler. Put using System;
outside the namespace.
CodePudding user response:
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, i-1);
}
if (i < high)
{
quickSort(i, high);
}
}
}
}