Jonathan
Jonathan

Reputation: 1

Why is my sorting algorithm producing an infinite loop? C#

ok, decided I would mess around and create a very basic Bubble sorting algorithm, I have only spent a couple hours, and this is only my second iteration of the program, and I'm kind of burnt out right now, and I seem to have hit a bit of a wall. I have it designed so that it will produce and display an Integer based on the number of transpositions it made on each round of sorting ( so I can keep an eye on it and make sure it is trending downward) and it is stuck in an infinite loop, returning the value '36' constantly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            bool sorted = false;
            int[] data = new int[100];
            data = GenerateData(data);

            while (sorted == false)
            {
                int count = Sort(data);
                if (count == 0)
                {
                    sorted = true;
                }
                else 
                {
                    Console.WriteLine("{0}", count);
                }
            }
        }

        public static int[] GenerateData(int[] data)
        {
            Random num = new Random();

            for (int x = 0; x < 100; x++)
            {
                data[x] = num.Next(0, 99);
            }
            return data;
        }

        public static int Sort (int[] data)
        {
            int TempA = 0;
            int TempB = 101;
            int count = 0;

            for (int x =0; x<100; x++)
            {
                TempA = data[x];

                if ((x + 1) < 100)
                {
                    TempB = data[(x + 1)];
                }

                else
                {
                    TempB = 101;
                }

                if ( TempA > TempB)
                {
                    data[x++] = TempA;
                    data[x] = TempB;
                    count++;
                }
            }
            return count;
        }        
    }
}

Upvotes: 0

Views: 132

Answers (1)

John Wu
John Wu

Reputation: 52280

I think there is something wrong with these two lines

data[x++] = TempA;
data[x] = TempB;

It should either be

data[x++] = TempA;
data[x--] = TempB;

Or

data[x+1] = TempA;
data[x] = TempB;

Otherwise your for loop will end up skipping elements.

Upvotes: 1

Related Questions