I am tring to improve on my bubble sort to make it more effiectiant. Anyone have any idea on how I could go upon doing this?

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Variables
            const int MAX = 20;
            int[] list = new int[MAX];
            Random r = new Random();

            //initialize
            fillArrayRandomly(ref list, r);
            printArrayHorizontally(list);
            fillArrayRandomly(ref list, r);
            printArrayVertically(list);

            //Calcualate
            bubbleSort(ref list);
            //Output
            printArrayVertically(list);
            //Freeze
            Console.ReadLine();
        }

        public static void fillArrayRandomly(ref int[] theList, Random r)
        {
            for (int i = 0; i < theList.Length; ++i)
            {
                theList[i] = r.Next(-101, 101);
            }
        }

        public static void bubbleSort(ref int[] a)
        {
            int i, j;
            for (i = 0; i < a.Length; ++i)
            {
                for (j = 0; j < a.Length - 1; ++j)
                {
                    if (a[j] > a[j + 1])
                    {
                        swap(ref a[j], ref a[j + 1]);
                    }
                }
            }
        }

        public static void swap(ref int x, ref int y)
        {
            int temp;

            temp = x;
            x = y;
            y = temp;
        }
        
        public static void printArrayVertically(int [] a)
        {
            Console.WriteLine();
            for(int i = 0; i < a.Length; ++i)
            {
                Console.WriteLine(a[i]);
            }
        }

        public static void printArrayHorizontally(int[] a)
        {
            Console.WriteLine();
            for (int i = 0; i < a.Length; ++i)
            {
                Console.Write(a[i] + " ");
            }
            Console.WriteLine();
        }
    }
}

Recommended Answers

All 2 Replies

If you only want array of integers to sort, you can do:

public static void bubbleSort(ref int[] a)
        {
            Array.Sort(a);
        }
commented: Thanks +0
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.