Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- /*
- * Insertion sorter
- **************************
- * Built by Starbeamrainbowlabs <https://starbeamrainbowlabs.com>
- * Binary available at https://starbeamrainbowlabs.com/binaries/reverseinsertion.exe
- *
- */
- public class InsertionSort
- {
- /// <summary>
- /// Swaps the values in an array of ints at the posistions a and b.
- /// </summary>
- /// <param name="array">A reference to the array to operate on.</param>
- /// <param name="a">The index of the first value.</param>
- /// <param name="b">The index of the second value.</param>
- static void swap_places(ref int[] array, int a, int b)
- {
- int temp = array[a];
- array[a] = array[b];
- array[b] = temp;
- }
- /// <summary>
- /// Generates a array of ints to a given size.
- /// </summary>
- /// <param name="size">The size of the array to generate</param>
- /// <param name="min">The minimum number that should appear in the array.</param>
- /// <param name="max">The maxmimum number that should appear in the array.</param>
- /// <returns>An array of random ints that is `size` in length.</returns>
- static int[] generate_array(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;
- }
- /// <summary>
- /// Prints an array of ints to the console.
- /// </summary>
- /// <param name="array">The array to print.</param>
- static void print_array(ref int[] array, bool new_line = true)
- {
- Console.Write("[ {0} ]", String.Join(", ", array));
- if (new_line)
- Console.WriteLine();
- }
- /// <summary>
- /// Performs an insertion sort in the array.
- /// </summary>
- /// <param name="array">A reference to the array to sort.</param>
- static void insertion_sort(ref int[] array)
- {
- /*
- * v
- * [1, 4, 2, 5, 3]
- * ¦
- *
- * v
- * [1, 4, 2, 3, 5]
- * ¦
- *
- * v
- * [1, 4, 2, 3, 5]
- * ¦
- *****************************
- * 0, 1, 2, 3, 4
- * v
- * [1, 2, 3, 4, 5]
- * ¦
- *
- * length: 5
- */
- for (int i = array.Length - 2; i >= 0; i--)
- {
- int shp = i;
- // |
- //make sure that we don't fall off the end of the array V
- while(shp < array.Length - 1 && array[shp] > array[shp + 1])
- {
- swap_places(ref array, shp, shp + 1);
- shp++;
- }
- Console.Write("i: {0} ", i);
- print_array(ref array);
- }
- }
- static void Main()
- {
- int[] array = generate_array(25, 0, 99);
- print_array(ref array);
- insertion_sort(ref array);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement