Home:ALL Converter>Bubble Sort Program

Bubble Sort Program

Ask Time:2018-11-19T08:12:53         Author:Zeze

Json Formatter

I am creating a bubble sort program which sorts random integers in an array. The array is supposed to be able to hold up to a million sorted integers. When I get to a high number (for example, 250,000) the program will sit there and never output anything. Code is below:

using System;

namespace SortingProject
{
    class MainClass
    {
        public static void Main(string[] args)
        {

            //create an array to hold integers
            int[] list = new int[50000];

            //call random function to populate integer values
            Random rand = new Random();

            //add integers to array
            for (int i = 0; i < list.Length; i++) {

                list[i] = rand.Next(1,50000);
            }

            //call bubble sort method and input the array
            BubbleSorting(list);

        }

        //bubble sort method and logic

        public static void BubbleSorting(int[] array)
        {

            //initialize time start 
            DateTime start = DateTime.Now;
            DateTime end;

            end = DateTime.Now;


            //initialize element integer
            int element = 0;

            for (int bubble = 0; bubble < array.Length; bubble++)
            {
                //create for loop to perform bubble sort
                for (int sort = 0; sort < array.Length - 1; sort++)
                {

                    if (array[sort] > array[sort + 1])
                    {
                        element = array[sort + 1];

                        array[sort + 1] = array[sort];

                        array[sort] = element;
                    }
                }

            }

            //loop and print array contents
            for (int i = 0; i < array.Length; i++)

                Console.Write(array[i] + " ");


            //calculate time it takes to sort array
            end = DateTime.Now;
            TimeSpan ts = end.Subtract(start);
            Console.WriteLine(" ");
            Console.WriteLine("Duration = {0} ms", ts.TotalMilliseconds);
        }
    }
    }

I usually wait for awhile while the program is running but it seems to be freezing with larger arrays. Any help on why would be greatly appreciated.

Author:Zeze,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/53366771/bubble-sort-program
yy