i wrote an application which is a custom console that allows execution of various commands. One of the commands allows sorting an array of integers. The input data is a string, which is a list of comma separated numbers.
My question is - how to minimize the sorting code runtime complexity as much as possible?
using System;
using System.Collections.Generic;
using CustomConsole.Common;
namespace Shell_Commander.Commands
{
class SortCommand : ICommand
{
private string _sortCommandName = "sort";
public string Name { get { return this._sortCommandName; } set { _sortCommandName = value; } }
public string Execute(string parameters)
{
var splittedParameters = parameters.Split(",",StringSplitOptions.RemoveEmptyEntries);
var arr = new List<int>();
int number;
int parameterIndex = 0;
foreach (var item in splittedParameters)
{
parameterIndex++;
if (int.TryParse(item, out number))
{
arr.Add(number);
}
else
{
Console.WriteLine($"The {parameterIndex}'st parameter isn't a number. Value: '{item}'.");
}
}
int temp = 0;
for (int write = 0; write < arr.Count; write++)
{
for (int sort = 0; sort < arr.Count - 1; sort++)
{
if (arr[sort] > arr[sort + 1])
{
temp = arr[sort + 1];
arr[sort + 1] = arr[sort];
arr[sort] = temp;
}
}
}
var result = "";
Console.Write("The sort result is: ");
for (int i = 0; i < arr.Count; i++)
{
result += arr[i] + " ";
Console.Write(arr[i] + " ");
}
Console.WriteLine();
return result;
}
}
}
Example - for the '4,1,2' input, the output will be:
"The sort result is: 1 2 4".