A
A
Albert Yaman2016-09-26 23:58:24
Programming
Albert Yaman, 2016-09-26 23:58:24

Bubble sort. First element?

1 sort element is not counted. What is the problem. Thanks in advance

class Program
    {

        static void Main(string[] args)
        {
            int[] mas = { 4, 5, 25, 21, 0, 8, 6, 97, 60, 46, 54 };
            Sort Ring = new Sort();
            foreach (int item in Ring.Search(mas))
            {
                Console.Write("{0}, ", item);
            }
            Console.ReadKey();
        }
    }
    class Sort
    {
        // Сортировка пузырьком
        public int[] Search(int[] gmas)
        {
            for (int i = 1; i < gmas.Length; i++)
            {
                if (gmas[i - 1] > gmas[i])
                {
                    int LastPoint = gmas[i];
                    gmas[i] = gmas[i - 1];
                    gmas[i - 1] = LastPoint;
                    i = 1;
                }

            }
            return gmas;
        }
    }

Output16b135db2e854019ac1ff69e32d352b3.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey, 2016-09-27
@albyaman

Try i = 1;replacing it with i = 0;
The point is that after the loop (after i=1;) will be executed i++.
UPD. Suddenly, someone else does not understand where to replace 1 with 0, I will give the full code:

class Program
    {

        static void Main(string[] args)
        {
            int[] mas = { 4, 5, 25, 21, 0, 8, 6, 97, 60, 46, 54 };
            Sort Ring = new Sort();
            foreach (int item in Ring.Search(mas))
            {
                Console.Write("{0}, ", item);
            }
            Console.ReadKey();
        }
    }
    class Sort
    {
        // Сортировка пузырьком
        public int[] Search(int[] gmas)
        {
            for (int i = 1; i < gmas.Length; i++)
            {
                if (gmas[i - 1] > gmas[i])
                {
                    int LastPoint = gmas[i];
                    gmas[i] = gmas[i - 1];
                    gmas[i - 1] = LastPoint;
                    i = 0; // заменяли только эту строчку
                }

            }
            return gmas;
        }
    }

Good luck everyone and be careful.

A
Alexander Volkov, 2016-09-27
@a_volkov1987

This is not bubble sort. That's bullshit. Look at the implementation wiki:
https://en.wikipedia.org/wiki/%D0%A1%D0%BE%D1%80%D...

public int[] Search(int[] gmas)
{
    for (int i = 0; i < gmas.length-1; i++) 
    {
        bool swapped = false;
        for (int j = 0; j < gmas.length-i-1; j++) 
        {
            if (gmas[j] > gmas[j+1]) 
            {
                int b = gmas[j]; 
                gmas[j] = gmas[j+1];
                gmas[j+1] = b;
                swapped = true;
            }
        }
        if(!swapped)
        break;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question