Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const int SIZE = 10; //the size of the array
- static void Sort()
- {
- int[] numbers = new int[SIZE];
- //input
- int input;
- for (int i = 0; i < numbers.Length; i++)
- {
- Console.WriteLine("Enter a number: ");
- input = int.Parse(Console.ReadLine());
- //sort
- InsertionSort(input, numbers, i);
- for (int j = 0; j < numbers.Length; j++)
- {
- Console.Write(numbers[i] + " ");
- }
- }
- //print
- for (int i = 0; i < numbers.Length; i++)
- {
- Console.WriteLine(numbers[i]);
- }
- }
- static void InsertionSort(int value, int[] numbers, int count)
- {
- /*
- * Insertion Sort algorithm:
- *
- * Takes three parameters - value (the number to be inserted), numbers (the array being sorted), and count (the number of items already inserted).
- *
- * The algorithm searches through the array for a number that's bigger than the value being inserted. Once the number is found, that number
- * and all the numbers after it are shifted to the right (there's no need to check for overflow; the last element is only filled when the array is
- * completely filled in, so it's never shifted), and the value is inserted into the number's position.
- *
- * If the algorithm is unable to find
- * a number bigger than the value, it means that the number being inserted is the biggest number in the array, meaning it needs to be inserted right after
- * all the numbers. This is where the count parameter comes in; the number is inserted at index count.
- *
- */
- bool inserted = false;
- for (int i = 0; (i < numbers.Length) && (!inserted); i++)
- {
- if (numbers[i] > value)
- {
- ShiftRight(numbers, i);
- numbers[i] = value;
- inserted = true; //number has been found (this also entails exiting the loop and the method)
- }
- }
- if (!inserted) //the number has not been inserted, meaning no value in the array exists that is bigger than the number
- {
- numbers[count] = value;
- }
- }
- static void ShiftRight(int[] numbers, int index)
- {
- for (int i = numbers.Length - 1; i > index; i--)
- {
- numbers[i] = numbers[i - 1];
- }
- numbers[index] = 0;
- }
- static void Main(string[] args)
- {
- Sort();
- }
Add Comment
Please, Sign In to add comment