简体   繁体   中英

Bubble sort swapping (C#)

I am applying bubble sort on an int array and it is working but on console (output) i want complete swapping for example int array:[3 2 5 4 1] and required output should be :

2 3 5 4 1  
2 3 4 5 1  
2 3 4 1 5  
2 3 1 4 5 

and in last the sorted int array

1 2 3 4 5.

Here is the code.

        int[] b = { 3, 2, 5, 4, 1 };
        int c;
        for (int p = 0; p <= b.Length - 2; p++)
        {
            for (int i = 0; i <= b.Length - 2; i++)
            {
                if (b[i] > b[i + 1])
                {
                    c = b[i + 1];
                    b[i + 1] = b[i];
                    b[i] = c;
                }
            }
        }
        foreach (int aa in b)
            Console.Write(aa + " ");
        Console.ReadLine();

Like this?

   int[] b = { 3, 2, 5, 4, 1 };
    int c;
    for (int p = 0; p <= b.Length - 2; p++)
    {
        for (int i = 0; i <= b.Length - 2; i++)
        {
            if (b[i] > b[i + 1])
            {
                c = b[i + 1];
                b[i + 1] = b[i];
                b[i] = c;

                foreach (int aa in b)
                  Console.Write(aa + " ");
                Console.WriteLine();
            }
        }
    }

    Console.ReadLine();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM