Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- class BubleSort
- {
- static void Main()
- {
- Random rnd = new Random();
- int[] array = new int[10];
- for (int i = 0; i < array.Length; i++)
- {
- array[i] = rnd.Next(101);
- }
- for (int i = 0; i < array.Length; i++)
- {
- Console.Write("{0,4}", array[i]);
- }
- Console.WriteLine();
- bool swapped = false;
- int counter = array.Length;
- do
- {
- counter--;
- int index = 0;
- int leftNumber = array[index];
- int rightNumber = array[index+1];
- for (int i = 0; i < counter; i++)
- {
- if (leftNumber> rightNumber)
- {
- //Switching positions.
- int temp = array[index];
- array[index] = array[index + 1]; //goes off in next loop.
- array[index + 1] = temp; //turns to be leftNumber in next loop.
- //Working with index's values.
- leftNumber = temp; //Getting the value of the higher number.
- if (i== counter-1) //For last iteration of the loop, when if leftNumber > rightNumber only exchanges their position.
- {
- swapped = true;
- break;
- }
- rightNumber = array[index + 2];
- }
- else
- {
- if (i == counter - 1) //For last iteration of the loop, when if leftNumber < ends the for loop.
- {
- swapped = true;
- break;
- }
- leftNumber = array[index + 1];
- rightNumber = array[index + 2];
- }
- index++;
- }
- } while (swapped && counter>1);
- for (int i = 0; i < array.Length; i++)
- {
- Console.Write("{0,4}", array[i]);
- }
- Console.WriteLine();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement