Simple bubble sort c#

245,460

Solution 1

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();

Solution 2

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;        
}

Solution 3

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;
    }

Solution 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();

Solution 5

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] + " ");
Share:
245,460
Karim O.
Author by

Karim O.

Updated on April 22, 2021

Comments

  • Karim O.
    Karim O. about 3 years
    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.

  • Karim O.
    Karim O. about 11 years
    To whoever suggested my Write is misplaced, thank you! That is what was causing things to get screwed up. Now it works
  • Polity
    Polity about 11 years
    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).
  • McAden
    McAden about 11 years
    @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. - en.wikipedia.org/wiki/Bubble_sort
  • Chris Panayotoff
    Chris Panayotoff over 10 years
    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));
  • 0x5C91
    0x5C91 almost 10 years
    Maybe write a short explanation as well.
  • Andrew
    Andrew over 9 years
    Please don't just post code. Explain what you're showing us.
  • Bart Czernicki
    Bart Czernicki over 9 years
    I agree with your feedback, but that is not a "traditional" bubble sort with the escape from the outer loop.
  • ManIkWeet
    ManIkWeet over 9 years
    This while loop example is slower than both the default BubbleSort and the early escape BubbleSort algorithms above with random unsorted data...
  • birdus
    birdus about 8 years
    Clear and self-documenting code doesn't need comments.
  • Hussain Patel
    Hussain Patel about 7 years
    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
    Hussain Patel about 7 years
    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; } } }
  • MiniMax
    MiniMax over 6 years
    It is not 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."
  • MindRoasterMir
    MindRoasterMir about 3 years
    where are you using write in the inner loop ? thanks
  • Matten
    Matten about 3 years
    @MindRoasterMir The first loop sorts the array, afterwards a second for-loop writes the results (the second-last line)