Esempio n. 1
0
        static void BubbleSort()
        {
            var List = new SortingList(10);

            List.Randomise();
            List.Print();

            while (true)                                     // loops forever until break is called
            {
                bool swapped = false;                        // init a boolean to track whether any swaps have been made
                for (int i = 0; i < List.Length - 1; i++)    // for the entirety of the list, minus one (so that the final element is not compared against nothing)
                {
                    if (List.list[i] > List.list[i + 1])     // compare the current element to the element to it's right
                    {
                        swapped = true;                      // sets the swapped bool to true indicating that a swap has been made
                        var tempvar = List.list[i];          // store the current element in the array
                        List.list[i]     = List.list[i + 1]; // overwrites the current element with the smaller value
                        List.list[i + 1] = tempvar;          // move the larger value to i + 1
                    }
                }
                List.Print();
                if (!swapped) // if swapped is false (indicating that no swaps have been made) the list is sorted
                {
                    break;    // break is called to end the loop
                }
            }
        }
Esempio n. 2
0
        static void InsertionSort()
        {
            var unsortedList = new SortingList(10);
            var sortedList   = new SortingList(unsortedList.Length);

            /* Let's fill the unsorted list with all sorts of junk */
            unsortedList.Randomise();
            unsortedList.Print();

            /* This is where we do the insertion sort-- doesn't
             * object oriented make this look easy? */

            for (int i = 0; i < unsortedList.Length; i++)
            {
                sortedList.Insert(unsortedList.Pop());
            }

            sortedList.Print();
        }