Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- /*
- * Bubble Sort
- * By Starbeamrainbowlabs (https://starbeamrainbowlabs.com/)
- *
- * Remove lines with '//debug' on them for normal use.
- */
- public class BubbleSort
- {
- public static void Main() {
- int[]tosort = generatearray(10, 0, 100);
- Console.Write("Original: ");
- printarray(tosort);
- Console.WriteLine();
- DoBubbleSort(tosort);
- }
- static void DoBubbleSort(int[]arraytosort) {
- int endingpoint = 1,
- temp;
- bool issorted;
- int swaps = 0,
- iterations = 0,
- passes = 0; //debug
- do {
- issorted = true;
- for(int i = arraytosort.Length - 1; i >= endingpoint; i--)
- {
- iterations++; //debug
- //Console.WriteLine("i: " + i + " i-1: " + (i - 1));
- if (arraytosort[i - 1] > arraytosort[i])
- {
- swaps++; //debug
- //swap the numbers around
- temp = arraytosort[i - 1];
- arraytosort[i - 1] = arraytosort[i];
- arraytosort[i] = temp;
- issorted = false;
- }
- }
- Console.Write("pass: " + passes + " ");
- printarray(arraytosort); //debug
- Console.WriteLine();
- passes++; //debug
- endingpoint++;
- } while (!issorted);
- Console.WriteLine("Sorting Complete!");
- Console.WriteLine("Statistics\n----------");
- Console.WriteLine("Passes: " + passes + ", Iterations: " + iterations + " Swaps: " + swaps);
- }
- static int[]generatearray(int size, int min = 0, int max = 25) {
- if (min >= max)
- throw new Exception("The min was bigger than max.");
- int[]newarray = new int[size];
- Random generator = new Random();
- for (int i = size - 1; i >= 0; i--) {
- newarray[i] = generator.Next(min, max);
- }
- return newarray;
- }
- static void printarray(int[]toprint) {
- Console.Write("[");
- for (int i = 0; i < toprint.Length; i++) {
- if (toprint[i] < 10) {
- //the number has only one character
- Console.Write(" ");
- }
- Console.Write(toprint[i]);
- if (i + 1 != toprint.Length) {
- Console.Write(", ");
- }
- }
- Console.Write("] ");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement