Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting string values without using any method/function

Tags:

c#

.net

I trying to do sorting without use of any method or function

My Code :

   string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };                     
   string name = string.Empty;
   Console.WriteLine("Sorted Strings : ");

   for (int i = 0; i < names.Length; i++)
        {
            for (int j = i + 1; j < names.Length; j++)
            {
                for (int c = 0; c < names.Length; c++)
                {
                    if (names[i][c] > names[j][c])
                    {
                        name = names[i];
                        names[i] = names[j];
                        names[j] = name;
                    }
                }

            }
            Console.WriteLine(names[i]);
        }

Please let me bring any solution for this code ?

In this code i am getting "Index was outside the bounds of the array" exception

like image 443
kasim Avatar asked Dec 14 '25 00:12

kasim


2 Answers

        int temp = 0;
        int[] arr = new int[] { 20, 65, 98, 71, 64, 11, 2, 80, 5, 6, 100, 50, 13, 9, 80, 454 };
        for (int i = 0; i < arr.Length; i++)
        {
            for (int j = i + 1; j < arr.Length; j++)
            {
                if (arr[i] > arr[j])
                {
                    temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
            Console.WriteLine(arr[i]);
        }
        Console.ReadKey();
like image 188
gevorg nanyan Avatar answered Dec 15 '25 14:12

gevorg nanyan


You need to implement a sorting algorithm.

A very simple algorithm you can implement is the insertion sort:

string[] names = { "Flag", "Nest", "Cup", "Burg", "Yatch", "Next" };

for (int i = 0; i < names.Length; i++)
{
    var x = names[i];
    var j = i;
    while(j > 0 && names[j-1].CompareTo(x) > 0)
    {
        names[j] = names[j-1];
        j = j-1;
    }
    names[j] = x;
}
like image 25
Alberto Avatar answered Dec 15 '25 14:12

Alberto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!