32
int[] arr = {800,11,50,771,649,770,240, 9};

int temp = 0;

for (int write = 0; write < arr.Length; write++)
{
    for (int sort = 0; sort < arr.Length - 1; sort++)
    {
        if (arr[sort] > arr[sort + 1])
        {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }       
    }   
    Console.Write("{0} ", arr[write]);  
}

All I am attempting to do is a simple bubble sort with this array. I would like to figure out why the sorting is screwed up. In example, here is when the array is {800,11,50,771,649,770,240, 9}:

Here is what gets displayed: 11, 50, 649, 9, 649, 770, 771, 800

I am thinking that I might be missing something in the comparison.

shekhar
  • 1,372
  • 2
  • 16
  • 23
Karim O.
  • 1,325
  • 6
  • 22
  • 36
  • You're outer loop goes from start to end, should be end to start! also you're inner loop should be limited to the value of write. – Polity Feb 08 '13 at 07:57
  • @Polity: I don't believe that's correct. As answers show, the outer loop is correct as is. You're right about the inner loop though. – George Duckett Apr 22 '13 at 10:18
  • 1
    I hope this is just an exercise in learning array manipulations though? I can't think of any application where a Bubble Sort would be the 'optimal' sorting strategy. If it's just for demonstration/mental exercise then fine, but if you're using this is a real-world application perhaps you should look at some other 'sort' algorithms. – Th3Minstr3l Feb 11 '13 at 11:05

18 Answers18

77

No, your algorithm works but your Write operation is misplaced within the outer loop.

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;

for (int write = 0; write < arr.Length; write++) {
    for (int sort = 0; sort < arr.Length - 1; sort++) {
        if (arr[sort] > arr[sort + 1]) {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

for (int i = 0; i < arr.Length; i++)
    Console.Write(arr[i] + " ");

Console.ReadKey();
Yi Zeng
  • 32,020
  • 13
  • 97
  • 125
Matten
  • 17,365
  • 2
  • 42
  • 64
14

This one works for me

public static int[] SortArray(int[] array)
{
    int length = array.Length;

    int temp = array[0];

    for (int i = 0; i < length; i++)
    {
        for (int j = i+1; j < length; j++)
        {
            if (array[i] > array[j])
            {
                temp = array[i];

                array[i] = array[j];

                array[j] = temp;
            }
        }
    }

    return array;        
}
azuneca
  • 1,053
  • 13
  • 15
  • Had almost the same solution: int[] unsorted = new int[]{ 3,4,13,1,18,22,2,100,11 }; //bubble sort for (int i = 0; i < unsorted.Length; i++) { for (var j = i + 1; j < unsorted.Length; j++) { if (unsorted[j] < unsorted[i]) { int temp = unsorted[j]; unsorted[j] = unsorted[i]; unsorted[i] = temp; } } } Console.WriteLine(String.Join(", ", unsorted)); – Chris Panayotoff Dec 22 '13 at 00:51
  • 2
    It is not [Bubble sort](https://en.wikipedia.org/wiki/Sorting_algorithm#Bubble_sort). From wikipedia: "The algorithm starts at the beginning of the data set. It compares the first two elements, and if the first is greater than the second, it swaps them. **It continues doing this for each pair of adjacent elements to the end of the data set.** It then starts again with the first two elements, repeating until no swaps have occurred on the last pass." – MiniMax Aug 31 '17 at 18:37
7
public static void BubbleSort(int[] a)
    {

       for (int i = 1; i <= a.Length - 1; ++i)

            for (int j = 0; j < a.Length - i; ++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 = x;
        x = y;
        y = temp;
    }
Fabio Antunes
  • 22,251
  • 15
  • 81
  • 96
Nikoo
  • 71
  • 1
  • 2
4
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;

for (int write = 0; write < arr.Length; write++)
{
    for (int sort = 0; sort < arr.Length - 1 - write ; sort++)
    {
        if (arr[sort] > arr[sort + 1])
        {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");

Console.ReadKey();
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
3

I saw someone use this example as part of a job application test. My feedback to him was that it lacks an escape from the outer loop when the array is mostly sorted.

consider what would happen in this case:

int[] arr = {1,2,3,4,5,6,7,8};

here's something that makes more sense:

int[] arr = {1,2,3,4,5,6,7,8};

int temp = 0;
int loopCount=0;
bool doBreak=true;

for (int write = 0; write < arr.Length; write++)
{
    doBreak=true;
    for (int sort = 0; sort < arr.Length - 1; sort++)
    {
        if (arr[sort] > arr[sort + 1])
        {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
            doBreak=false;
        }
        loopCount++;
    }
    if(doBreak){ break; /*early escape*/ }
}

Console.WriteLine(loopCount);
for (int i = 0; i < arr.Length; i++) Console.Write(arr[i] + " ");
Dima
  • 63
  • 6
1
public static int[] BubbleSort(int[] arr)
{
   int length = arr.Length();

   while (length > 0)
   {
      int newLength = 0;
      for (int i = 1; i < length; i++)
      {
         if (arr[i - 1] > arr[i])
         {
            Swap(ref arr[i - 1], ref arr[i]); 
            newLength = i;   
         }   
      }
      length = newLength;
   }
}

public static void Swap(ref int x, ref int y)
{
   int temp = y;
   y = x;
   x = temp;
}
H A
  • 1,251
  • 2
  • 24
  • 39
1

I wanted to add to the accepted answer something different: Number of iterations can be reduced as well, as below.

int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };

int temp = 0;
int arrLength = arr.Length;

for (int write = 0; write < arr.Length - 1; write++, arrLength--)
{
    for (int sort = 0; sort < arrLength - 1; sort++)
    {
        if (arr[sort] > arr[sort + 1])
        {
            temp = arr[sort + 1];
            arr[sort + 1] = arr[sort];
            arr[sort] = temp;
        }
    }
}

foreach (var item in arr)
{
    Console.WriteLine(item);
}
Serhat Ates
  • 885
  • 1
  • 12
  • 18
0

Your Console.Write("{0} ", arr[write]); is too early. You're printing the values while the sort is still in progress. For example, you're printing 9 as being index 3 in the array, yet on the very next iteration of the loop the 9 has moved to index 2 and 240 has moved to index 3... yet you're outer loop has moved forward so it prints 649 the second time and 240 never gets printed.

McAden
  • 13,714
  • 5
  • 37
  • 63
  • This is not really true, He's printing out the last written value. This does mean that after the fix, the result will be printed in a descended order (although sorted). – Polity Feb 08 '13 at 08:45
  • @Polity - `He's printing out the last written value.` - I think you misunderstand a 'Bubble Sort'. He's clearly outputting values to the console before the algorithm is finished sorting. There's nothing wrong with the actual sort logic above provided that he simply wanted to implement a bubble sort. - http://en.wikipedia.org/wiki/Bubble_sort – McAden Feb 08 '13 at 18:09
0
int[] array = new int[10] { 13, 2, 5, 8, 23, 90, 41, 4, 77, 61 };

for (int i = 10; i > 0; i--)
{
    for (int j = 0; j < 9; j++)
    {
        if (array[j] > array[j + 1])
        {
            int temp = array[j];
            array[j] = array[j + 1];
            array[j + 1] = temp;
        }
    }
}
OGHaza
  • 4,795
  • 7
  • 23
  • 29
rsrdjan
  • 1
  • 1
0
    static bool BubbleSort(ref List<int> myList, int number)
    {
        if (number == 1)
            return true;
        for (int i = 0; i < number; i++)
        {
            if ((i + 1 < number) && (myList[i] > myList[i + 1]))
            {
                int temp = myList[i];
                myList[i] = myList[i + 1];
                myList[i + 1] = temp;
            }
            else
                continue;
        }
        return BubbleSort(ref myList, number - 1);
    }
0

Just another example but with an outter WHILE loop instead of a FOR:

public static void Bubble()
    {
        int[] data = { 5, 4, 3, 2, 1 };
        bool newLoopNeeded = false;
        int temp;
        int loop = 0;

        while (!newLoopNeeded)
        {
            newLoopNeeded = true;
            for (int i = 0; i < data.Length - 1; i++)
            {
                if (data[i + 1] < data[i])
                {
                    temp = data[i];
                    data[i] = data[i + 1];
                    data[i + 1] = temp;
                    newLoopNeeded = false;
                }
                loop++;
            }
        }
    }
RolandoCC
  • 868
  • 1
  • 14
  • 19
  • 1
    This while loop example is slower than both the default BubbleSort and the early escape BubbleSort algorithms above with random unsorted data... – ManIkWeet Jan 16 '15 at 08:17
0

Bubble sort with sort direction -

using System;

public class Program
{
    public static void Main(string[] args)
    {
        var input = new[] { 800, 11, 50, 771, 649, 770, 240, 9 };

        BubbleSort(input);

        Array.ForEach(input, Console.WriteLine);

        Console.ReadKey();
    }

    public enum Direction
    {
        Ascending = 0,
        Descending
    }

    public static void BubbleSort(int[] input, Direction direction = Direction.Ascending)
    {
        bool swapped;
        var length = input.Length;

        do
        {
            swapped = false;
            for (var index = 0; index < length - 1; index++)
            {
                var needSwap = direction == Direction.Ascending ? input[index] > input[index + 1] : input[index] < input[index + 1];

                if (needSwap)
                {
                    var temp = input[index];
                    input[index] = input[index + 1];
                    input[index + 1] = temp;
                    swapped = true;
                }
            }
        } while (swapped);
    }
}
Parag Meshram
  • 8,281
  • 10
  • 52
  • 88
0

This is what I wrote using recursive methods:

    public static int[] BubbleSort(int[] input)
    {
        bool isSorted = true;
        for (int i = 0; i < input.Length; i++)
        {
            if (i != input.Length - 1 && input[i] > input[i + 1])
            {
                isSorted = false;
                int temp = input[i];
                input[i] = input[i + 1];
                input[i + 1] = temp;
            }
        }
        return isSorted ? input : BubbleSort(input);
    }
Arad Alvand
  • 8,607
  • 10
  • 51
  • 71
0

It does the same in a more elegant way.

var arrayValues = new[] { 99, 12, 11, 300, 400, 10, 9, 3, 6, 5, 7, 8};
for (var mainLoop = 0; mainLoop < arrayValues.Length; mainLoop++)
{
   for (var innerLoop = mainLoop + 1; innerLoop < arrayValues.Length; innerLoop++)
   {
       if (arrayValues[mainLoop] <= arrayValues[innerLoop])
       {
         continue;
       }

       var temp = arrayValues[mainLoop];
       arrayValues[mainLoop] = arrayValues[innerLoop];
       arrayValues[innerLoop] = temp;
  }
}
André Mendonça
  • 658
  • 8
  • 13
0

So i did mine as a recursive function (no need for the nested loop), perhaps someone could comment if this is inefficient (when compared to the other solutions).

    public static int[] BubbleSort(int[] arrayOfValues)
    {
        var swapOccurred = false;
        
        for (var i = 0; i < arrayOfValues.Length; i++)
        {
            if (i == arrayOfValues.Length - 1)
                continue;

            if (arrayOfValues[i] > arrayOfValues[i + 1])
            {
                //swap values
                var current = arrayOfValues[i];
                var next = arrayOfValues[i + 1];
                
                arrayOfValues[i] = next;
                arrayOfValues[i + 1] = current;

                swapOccurred = true;
            }
        }

        if (swapOccurred)
        {
            // keep going until no further swaps are required:
            BubbleSort(arrayOfValues);
        }

        return arrayOfValues;
    }
Alex
  • 154
  • 2
  • 14
-1
int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 };
for (int i = 0; i < arr.Length; i++)
{
    for (int j = i; j < arr.Length ; j++)
    {
        if (arr[j] < arr[i])
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
}
Console.ReadLine();
fubo
  • 44,811
  • 17
  • 103
  • 137
  • 1
    this is wrong, the above code you have shown is selection sort- not bubble sort.. in bubble sort you move be comparing adjacent elements.. please update it . for (int i = 0; i < arr.Length; i++) { for (int j = 0; j < arr.Length-1 ; j++) { if (arr[j] > arr[j+i]) { int temp = arr[j+1]; arr[j+1] = arr[j]; arr[j] = temp; } } } – Hussain Patel Feb 08 '17 at 16:35
-1
   using System; 
 using System.Collections.Generic; 
 using System.Linq;  
using System.Text; 
 using System.Threading.Tasks;

namespace Practice {
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter the size");
            int n = Convert.ToInt32(Console.ReadLine());
            int[] mynum = new int[n];
            Console.WriteLine("Enter the Numbers");
            for (int p = 0; p < n;p++ )
            {
                mynum[p] = Convert.ToInt32(Console.ReadLine());

            }
            Console.WriteLine("The number are");
                foreach(int p in mynum)
                {
                    Console.WriteLine(p);
                }
                for (int i = 0; i < n;i++ )
                {
                    for(int j=i+1;j<n;j++)
                    {
                        if(mynum[i]>mynum[j])
                        {
                            int x = mynum[j];
                            mynum[j] = mynum[i];
                            mynum[i] = x;
                        }
                    }
                }
                Console.WriteLine("Sortrd data is-");
            foreach(int p in mynum)
            {
                Console.WriteLine(p);
            }
                    Console.ReadLine();
        }
    } }
Debendra Dash
  • 5,334
  • 46
  • 38
  • 1
    Its wrong - you are showing selection sort here. You are comparing first element I = 0 with every element of j = I+1 this is selection sort and not bubble sort.. in bubble sort for every pass the first element j = is compared with j + 1 and if not in order it is swapped, this will be done for every pass on i. Please check the for loop of your and the first answer from matten – Hussain Patel Feb 07 '17 at 11:49
-1
    public void BubbleSortNum()
    {
        int[] a = {10,5,30,25,40,20};
        int length = a.Length;
        int temp = 0; 
        for (int i = 0; i <length; i++)
        {               
            for(int j=i;j<length; j++)
            {
                if (a[i]>a[j])
                {
                    temp = a[j];
                    a[j] = a[i];
                    a[i] = temp;
                }     
            }
           Console.WriteLine(a[i]);
        }       
     }
mpaul
  • 27
  • 5