Home Ask Login Register

Developers Planet

Your answer is one click away!

lookat thisguy February 2016

Arranging numbers c# code

Can someone help fix this code? It's supposed to arrange the numbers in order so from lowest to highest. However im having trouble running the code...it wont print anything either. thanks

class Program
{
    static void Main(string[] args)
    {
        int[] IN_AR_Numbers = { 3, 2, 1, 6, 5, 4, 9, 8, 7 };

        PrintArray(IN_AR_Numbers);
        BubbleSort(IN_AR_Numbers);
        Console.ReadLine();
    }

    static void BubbleSort(int[] IN_AR_NumbersSorted)
    {
        int IN_Temp = 0;
        bool BL_HasSwapped = false;
        int IN_Swapcount = 0;

        do
        {
            BL_HasSwapped = false;

            for (int j = 0; j < IN_AR_NumbersSorted.Length - 1; j++)
            {
                if (IN_AR_NumbersSorted[j] > IN_AR_NumbersSorted[j + 1])
                {
                    IN_Temp = IN_AR_NumbersSorted[j + 1];
                    IN_AR_NumbersSorted[j + 1] = IN_AR_NumbersSorted[j];
                    IN_AR_NumbersSorted[j] = IN_Temp;
                    BL_HasSwapped = true;
                    IN_Swapcount++;
                }
            }
        }
        while (BL_HasSwapped);

        PrintArray(IN_AR_NumbersSorted);
    }
}

Answers


NikolaiDante February 2016

Your not writing anything out in the code given.

using System;

public class Program
{
    public static void Main(string[] args)
    {
        int[] IN_AR_Numbers = { 3, 2, 1, 6, 5, 4, 9, 8, 7 };

        BubbleSort(IN_AR_Numbers);

        foreach (var i in IN_AR_Numbers)
        {
            Console.WriteLine(i);
        }

        Console.ReadLine();
    }

    static void BubbleSort(int[] IN_AR_NumbersSorted)
    {
        int IN_Temp = 0;
        bool BL_HasSwapped = false;
        int IN_Swapcount = 0;

        do
        {
            BL_HasSwapped = false;

            for (int j = 0; j < IN_AR_NumbersSorted.Length - 1; j++)
            {
                if (IN_AR_NumbersSorted[j] > IN_AR_NumbersSorted[j + 1])
                {
                    IN_Temp = IN_AR_NumbersSorted[j + 1];
                    IN_AR_NumbersSorted[j + 1] = IN_AR_NumbersSorted[j];
                    IN_AR_NumbersSorted[j] = IN_Temp;
                    BL_HasSwapped = true;
                    IN_Swapcount++;
                }
            }
        }
        while (BL_HasSwapped);
    }   
}

Gives

1 2 3 4 5 6 7 8 9

I removed the PrintArray function that isn't in the code as given and added a loop to write the array out:

foreach (var i in IN_AR_Numbers)
{
  Console.WriteLine(i);
}

(fiddle)

Post Status

Asked in February 2016
Viewed 3,881 times
Voted 7
Answered 1 times

Search




Leave an answer


Quote of the day: live life