my Bubble Sort does not work well nor a

Asked

Viewed 93 times

2

Code:

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

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            int q = Convert.ToInt32(Console.ReadLine());
            string arrays = Console.ReadLine();
            string[] arraysint = new string[q];
            arraysint = arrays.Split(' ');
            int[] numbers = Array.ConvertAll(arraysint, int.Parse);
            int i;
            int save = 0;
            int j;
            int temp;
            int current = q - 1;
            int[] maior = new int[1];
            //int[] numbers = new int[q];
            for (j = 0; j < q; j++)
            { 
              for (i = 0; i < current + 1; i++)

                {
                        if (current == 1)
                    {
                        goto final;
                    }
                    if (i == current)
                        {
                      if (current == save)
                        {
                            current--;  
                        }
                        if (current < q - 1)
                        {
                            if (maior[0] == numbers[current] && maior[0] != 0)
                            {
                                current--;
                            }
                        }
                        temp = numbers[current];
                        numbers[save] = temp;
                     numbers[current] = maior[0];
                    current--;
                    }

               if (maior[0] < numbers[i])
                {
                        save = i;
                    maior[0] = numbers[i];       
                }

            }
                maior[0] = 0;
            }
        final:
            Console.Clear();
            for (i = 0; i < q; i++)
            {
                Console.Write(numbers[i] + " ");

            }
            Console.ReadKey();
        }
    }
}

input:

5
5 4 3 2 1  

Output:

1 3 2 4 5

I’ve done everything, but I can’t fix it. Somebody help me there?

  • You’ve made it very difficult, considering Bubble Sort are 2 for and 1 if with a swap, literally 6 lines of code. Several things don’t make much sense, such as using an array with a house for the maior when you can use a normal variable. Even the notion of maior for this algorithm is not necessary. The same can be said for goto, which makes it difficult to visualize the flow of the program. I would personally advise you to start again, calmly and think about the logic required for the algorithm, which is much simpler than what you have at the moment.

1 answer

2


As our friend @Isac commented, you have quite complicated the logic of Bubble Sort. I will leave below a class that performs the ordering Bubble Sort, evaluate how it works and try to redo your exercise by studying each point of the algorithm.

/// <summary>
/// Classe responsável pelas técnicas de ordenação Bubble Sort
/// </summary>
public class BubbleSort
{
    /// <summary>
    /// Ordena um vetor de números inteiros utilizando o algoritmo de Bubble Sort
    /// </summary>
    /// <param name="vetor">Vetor que será ordenado</param>
    /// <returns>Vetor ordenado</returns>
    public static int[] Ordernar(int[] vetor)
    {
        //Variável auxiliar que irá armazenar temporariamente um valor do vetor
        int numeroAuxiliar = 0;
        //Variável para informar se houve alguma troca no algoritmo, caso não houver troca significa que o vetor já está ordenado, então não precisamos continuar o processamento.
        bool trocou = false;

        // i determina o número de etapas para a ordenação
        for (int i = 0; i < vetor.Length - 1; i++) 
        {
            trocou = false;

            // j determina o número de comparações em cada etapa e os índices a serem pesquisados para a comparação. 
            for (int j = 0; j < vetor.Length - (i + 1); j++)
            {
                if (vetor[j] > vetor[j + 1])
                {
                    trocou = true;
                    numeroAuxiliar = vetor[j];
                    vetor[j] = vetor[j + 1];
                    vetor[j + 1] = numeroAuxiliar;
                }
            }

            //Se não houve troca podemos parar a execução do algoritmo de ordenação para evitarmos o processamento desnecessário
            if (!trocou)
                break;
        }

        return vetor;
    }

To call the sort method Bubble Sort just do the following:

//Exemplo da chamada do método de ordenação
int[] vetor = {5, 4, 3, 2, 1};

BubbleSort.Ordernar(vetor);
  • worth I refilled it and then ran my mistake was that I was just putting the biggest number last instead of testing each one for (j = 0; j < q; j++)&#xA; {&#xA; for (i = 0; i < q; i++)&#xA; {&#xA; if (i < 4)&#xA; {&#xA; if (numbers[i] > numbers[i + 1])&#xA; {&#xA; temp = numbers[i];&#xA; numbers[i] = numbers[i + 1];&#xA; numbers[i + 1] = temp;&#xA;}&#xA;}&#xA;}&#xA;}&#xA; Console.WriteLine(string.Join(" ", numbers));

  • No reason, I’m glad you made it. Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.