Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple bubble sort c#

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.

like image 790
Karim O. Avatar asked Feb 08 '13 07:02

Karim O.


People also ask

What is bubble sort in C with example?

Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until they are in the intended order. Just like the movement of air bubbles in the water that rise up to the surface, each element of the array move to the end in each iteration. Therefore, it is called a bubble sort.

What is bubble sort simple example?

Bubble sort starts with very first two elements, comparing them to check which one is greater. ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

How do you implement bubble sort?

Implementing Bubble Sort Algorithm Starting with the first element(index = 0), compare the current element with the next element of the array. If the current element is greater than the next element of the array, swap them. If the current element is less than the next element, move to the next element. Repeat Step 1.


1 Answers

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(); 
like image 166
Matten Avatar answered Sep 22 '22 06:09

Matten