0

I have array of integers with repeating values. I need to sort it in decreasing order and print 2 lines.

Algorythm:

  • index = 0;
  • Find largest value in array
  • Print out its original index via Console.Write($"{maxPos} ");
  • Switch it with element with first value with index
  • Repeat for all other elements in array
  • Print out sorted array using Console.Write($"{a[i]} ");)

Trouble is I can't get the index printed in console no mater what.

using System;

public class SortProblem
{
    public static void Main()
    {
        Sort();
    }

    public static void Sort()
    {
        var array = new [] 
        {
            10, 10, 5, 2, 2, 5, 6, 7, 8, 15, 4, 4, 4, 2, 3, 5, 5, 36, 32, 623, 7, 475, 7, 2, 2, 44, 5, 6, 7, 71, 2 
        };

        for (int index = 0; index < array.Length -1; index++)
        {
            int max = index;

            for (int elemIndex = index+1; elemIndex < array.Length; elemIndex++)
            {
                if (array[elemIndex] > array[max])
                {
                    max = elemIndex;
                }
            }

            int tmp = array[index];
            array[index] = array[max];
            array[max] = tmp;
        }

        foreach (int element in array) 
        {
            Console.Write (element+" ");
        }
    }
}

Expected output is:

19 21 29 25 17 18 9 19 21 21 19 20 22 28 21 27 16 18 26 27 29 22 27 29 27 25 26 27 28 29 30 623 475 71 44 36 32 15 10 10 8 7 7 7 7 6 6 5 5 5 5 5 4 4 4 3 2 2 2 2 2 2

7
  • your question is not clear Commented Nov 3, 2016 at 11:22
  • Will help to see what is the expected output for that array Commented Nov 3, 2016 at 11:26
  • @GiladGreen added expected output Commented Nov 3, 2016 at 11:34
  • With regard to expected output: How is it that, given array size 31, you expect 62 numbers to print? If you were trying to say the output is the second line of your "expected output", with the first line being the indices for those numbers, then the first line could not have duplicate values (an array index obviously can not index to two different elements in the array). Commented Nov 3, 2016 at 11:55
  • @MichaelGorsich First line is just list of indexes of largest elements in array on each step of the loop (first largest is 623 and it's original position in array is 19, next one will be 475 with original position 21 and so on). Second line is sorted array itself. Commented Nov 3, 2016 at 12:03

2 Answers 2

1

The simplest solution:

using System;
using System.Linq;

public class SortProblem
{
    public static void Main()
    {
        var result = new[]
        {
            10, 10, 5, 2, 2, 5, 6, 7, 8, 15, 4, 4, 4, 2, 3, 5, 5, 36, 32, 623, 7, 475, 7, 2, 2, 44, 5, 6, 7, 71, 2
        }.Select((element, idx) => new { Value = element, OriginalIndex = idx }).OrderByDescending(item => item.Value).ToList(); // The last one only needed to persist the result set and avoid double processing

        Console.WriteLine(string.Join(" ", result.Select(item => item.OriginalIndex)));
        Console.WriteLine(string.Join(" ", result.Select(item => item.Value)));
    }
}

But to refer back to your algorithm:

using System;
using System.Text;

public class SortProblem
{
    public static void Main()
    {
        Sort();
    }

    private static void Sort()
    {
        StringBuilder sb = new StringBuilder(); 

        var array = new[]
        {
            10, 10, 5, 2, 2, 5, 6, 7, 8, 15, 4, 4, 4, 2, 3, 5, 5, 36, 32, 623, 7, 475, 7, 2, 2, 44, 5, 6, 7, 71, 2
        };

        for (int i = 0; i < array.Length; ++i)
        {
            int max = i;

            for (int j = i + 1; j < array.Length; ++j)
                if (array[max] < array[j])
                    max = j;

            sb.Append(max);
            sb.Append(" ");

            int temp = array[i];
            array[i] = array[max];
            array[max] = temp;
        }

        Console.WriteLine(sb.Remove(sb.Length - 1, 1).ToString());
        Console.WriteLine(string.Join(" ", array));
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Second chunk of code did job just right. Best of luck to you, sir!
1
using System;

public class SortProblem
{
    public static void Main()
    {
        Sort();
        Console.ReadKey();
    }
    public static void Sort()
    {
        var a = new[]
        {
            10, 10, 5, 2, 2, 5, 6, 7, 8, 15, 4, 4, 4, 2, 3, 5, 5, 36, 32, 623, 7, 475, 7, 2, 2, 44, 5, 6, 7, 71, 2
        };
        Max_elements(a);
        Console.WriteLine();
        Sort_elements(a);
    }
    private static void Max_elements(int[] a)
    {
        /*"індекс" = 0 */
        for (int index = 0; index < a.Length; index++)
        {
            /*Знаходить у списку найбільше значення таке,
             *що його позиція дорівнює або більша за "index"
             *(справа від елемента на позиції "індекс")*/
            int maxPos = index, tmp;
            /* відсортує заданий масив "a"
             * у порядку спадання "elemIndex < a"
             * за допомогою алгоритму сортування вибором ".Length"*/
            for (int elemIndex = index + 1; elemIndex < a.Length; elemIndex++)
            {
                /*Якщо елемент на позиції elemIndex
                 *більше елемента на позиції maxPos,
                 *то необхідно онвити значення "індекс"*/
                if (a[elemIndex] > a[maxPos])
                {
                    maxPos = elemIndex;
                }
            }
            /*Міняє його місцями з елементом масиву на позиції "індекс"*/
            tmp = a[index];
            a[index] = a[maxPos];
            a[maxPos] = tmp;
            /*виводимо всі позиції максимального елемента і пробіл після неї*/
            Console.Write($"{maxPos} ");
            /*Рядок, який передує символ $ називається Інтерпольований рядок.
             Інтерпольовані рядки можуть містити вирази взяті у фігурні дужки {}*/
        }
    }

    private static void Sort_elements(int[] a)
    {
        for (int i = 0; i < a.Length; i++)
        {
            /*виводимо всі елементи відсортованого масиву і пробіл після неї*/
            Console.Write($"{a[i]} ");
        }
    }   
}

1 Comment

While the code may answer the question, it's always best to include an explanation and relevant references when possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.