Solved

C# Sorting Use Switch(Sort Type) instead of the if else if else if else.

Posted on 2010-09-05
12
827 Views
Last Modified: 2012-05-10
Experts I have a project I am building as part of a CIS class. I have the Program class built using using if else statements. These program is set up so user's can select the type of sort they want use. I would like to replace these if else statements in the attached code with Switch.

Can someone show me how to do this?
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace CIS110Project

{

    class Program

    {

        static void Main(string[] args)

        {

            int SortType = 0;

            Console.WriteLine("What would you like to do today?");

            Console.WriteLine("Enter 1 for Bubble Sort.");

            Console.WriteLine("Enter 2 for Selection Sort.");

            Console.WriteLine("Enter 3 for Insertion Sort.");

            SortType = Convert.ToInt16(Console.ReadLine());



            int numbers = 0;

            Console.WriteLine("How many numbers do you want to sort?");

            numbers = Convert.ToInt16(Console.ReadLine());

            Console.WriteLine("Your random numbers are");

            int[] ranNum = new int[numbers];

            Random RandomNumber = new Random();

           

            for (int i = 0; i < numbers; i++)

            {

                ranNum[i] = RandomNumber.Next(100);



                Console.WriteLine(ranNum[i]);

            }

           

           if (SortType == 1)

            {

               BubbleSrt mynewobj = new BubbleSrt();

               mynewobj.BubbleSortStoB(ranNum);

               mynewobj.BubbleSortBtoS(ranNum);

            }

           

          else if (SortType == 2)

            {

              SelectionSrt mynewobj = new SelectionSrt();

              mynewobj.SelectionSortStoB(ranNum);

              mynewobj.SelectionSortBtoS(ranNum);

            }

         else if (SortType == 3)

            {

              InsertionSrt mynewobj = new InsertionSrt();

              mynewobj.InsertionSortStoB(ranNum);

              mynewobj.InsertionSortBtoS(ranNum);

            }

            

          else

            {

                Console.WriteLine("Invalid choice!!!!!!!");

                Console.ReadLine();

            }

        }

    }

}

Open in new window

0
Comment
Question by:vzdog
  • 7
  • 4
12 Comments
 
LVL 65

Expert Comment

by:rockiroads
Comment Utility
format of switch statement is like this

switch (SortType) {
case SORT_TYPE_A:
   your code ....;
   break;
case SORT_TYPE_B:
   your code ....;
   break;
default:
   your code ....;
   break;
}


So instead of using hardcoded numbers, define constants and use them

const int SORT_TYPE_A = 1;


Give constants a meaningful name though
0
 
LVL 65

Expert Comment

by:rockiroads
Comment Utility
The default is used when you want to do something if the value you are testing against is not handled


const int BUBBLE_SORT = 1;
	const int SELECTION_SORT = 2;
	const int INSERTION_SORT = 3;

	switch (SortType) {
		case BUBBLE_SORT:
			BubbleSrt mynewobj = new BubbleSrt();
			mynewobj.BubbleSortStoB(ranNum);
			mynewobj.BubbleSortBtoS(ranNum);
			break;

		case SELECTION_SORT:
			SelectionSrt mynewobj = new SelectionSrt();
			mynewobj.SelectionSortStoB(ranNum);
			mynewobj.SelectionSortBtoS(ranNum);
			break;

		case INSERTION_SORT:
			InsertionSrt mynewobj = new InsertionSrt();
			mynewobj.InsertionSortStoB(ranNum);
			mynewobj.InsertionSortBtoS(ranNum);
			break;

		default:
			Console.WriteLine("Invalid choice!!!!!!!");
			Console.ReadLine();
	}

Open in new window

0
 

Author Comment

by:vzdog
Comment Utility
rockiroads what would I need to add to show at the end of the sor what method was used?
0
 
LVL 65

Expert Comment

by:rockiroads
Comment Utility
We could then define a string array and use the index of that array to identify the selection
0
 
LVL 65

Expert Comment

by:rockiroads
Comment Utility
or just set a flag within the case statement. how are you wanting to display the sort selection?
0
 

Author Comment

by:vzdog
Comment Utility
Basically after the results of the sort I would just like to show the sort type the user selected.

This is part on a basic programming design class, the instructor got a little bit ahead of us using C#.

Here is what we are trying to accomplsh:

Use a windows for for the user to select what sort method they want to use:
1) Bubble
2) Insert
3) Selection

From there would actuall display the results in the firm and give the user the opportunity to a Binary Search.

If it sounds confusing it is - to me any way.

I have all the individual sort codes but no idea how to tie it all together.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 65

Expert Comment

by:rockiroads
Comment Utility
here is an example using arrays

here we define our string array, remember subscript starts from zero
            string[] sortTypes = new string[] { "Bubble Sort", "Selection Sort", "Insertion Sort" };

so we define constants for use with our switch statement, the value represents the subscript index of the array
            const int BUBBLE_SORT = 0;
            const int SELECTION_SORT = 1;
            const int INSERTION_SORT = 2;


and example on how we use it
            MessageBox.Show(sortTypes[BUBBLE_SORT]);

because your variable SortType starts from 1, remember to subtract 1 from it when checking the value against the constants
0
 
LVL 65

Expert Comment

by:rockiroads
Comment Utility
If you are just a beginner, the above might be advanced possibly

so here is the other simple way

How you have defined a variable called SortType, create one called SortDescription
then in the switch statement, set SortDescription the string you want to display

then simply show SortDescription

0
 
LVL 85

Expert Comment

by:Mike Tomlinson
Comment Utility
You could use an ENUM instead, and  then just call ToString() on it!...
http://msdn.microsoft.com/en-us/library/sbbt4032(VS.71).aspx
0
 

Author Comment

by:vzdog
Comment Utility
yes too advanced - I am not even a beginner .
0
 
LVL 65

Accepted Solution

by:
rockiroads earned 500 total points
Comment Utility
ok, to try code as a beginner, this code dumps the selection you made.
better would be to define a string variable, assign that a value then dump that just once but that is something you could do. Don't want to make the code nice and advanced else your teacher may know something isn't right lol


	const int BUBBLE_SORT = 1;

	const int SELECTION_SORT = 2;

	const int INSERTION_SORT = 3;



	switch (SortType) {

		case BUBBLE_SORT:

			BubbleSrt mynewobj = new BubbleSrt();

			mynewobj.BubbleSortStoB(ranNum);

			mynewobj.BubbleSortBtoS(ranNum);

			Console.WriteLine ("Bubble Sort Selected");

			break;



		case SELECTION_SORT:

			SelectionSrt mynewobj = new SelectionSrt();

			mynewobj.SelectionSortStoB(ranNum);

			mynewobj.SelectionSortBtoS(ranNum);

			Console.WriteLine ("Selection Sort Selected");

			break;



		case INSERTION_SORT:

			InsertionSrt mynewobj = new InsertionSrt();

			mynewobj.InsertionSortStoB(ranNum);

			mynewobj.InsertionSortBtoS(ranNum);

			Console.WriteLine ("Insertion Sort Selected");

			break;



		default:

			Console.WriteLine("Invalid choice!!!!!!!");

			Console.ReadLine();

	}

Open in new window

0
 

Author Comment

by:vzdog
Comment Utility
Rockiroads - I will be using thesolution you provided but was wondering if you could take a look at the code snipet I found that utilizes a GUI Window.  I want to know if this would partly be the solution to start my programs from a Windows form by the user.

Thanks for your asisstance.
// sorting an integer array's values in ascending order

// a Windows GUI program with a button and label

// compiled with C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe



using System;

using System.Windows.Forms;  // GUI stuff



namespace BubbleSorterSpace

{

   public class BubbleSorter : System.Windows.Forms.Form

   {

      private System.Windows.Forms.Button sortButton;

      private System.Windows.Forms.Label resultLabel;

      // required designer variable

      private System.ComponentModel.Container components = null;



      public BubbleSorter()

      {

         // required for GUI support

         InitializeComponent();

      }



      // clean up any resources being used

      protected override void Dispose( bool disposing )

      {

         if ( disposing )

         {

            if (components != null) 

            {

               components.Dispose();

            }

         }

         base.Dispose( disposing );

      }



      private void InitializeComponent()

      {

         this.sortButton = new System.Windows.Forms.Button();

         this.resultLabel = new System.Windows.Forms.Label();

         this.SuspendLayout();

         // 

         // sortButton

         // 

         this.sortButton.Location = new System.Drawing.Point(109, 8);

         this.sortButton.Name = "sortButton";

         this.sortButton.TabIndex = 0;

         this.sortButton.Text = "Sort Data";

         this.sortButton.Click += new System.EventHandler(this.sortButton_Click);

         // 

         // resultLabel

         // 

         this.resultLabel.Location = new System.Drawing.Point(8, 40);

         this.resultLabel.Name = "resultLabel";

         this.resultLabel.Size = new System.Drawing.Size(280, 64);

         this.resultLabel.TabIndex = 1;

         // 

         // the Window Form

         // 

         this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);

         this.ClientSize = new System.Drawing.Size(292, 109);

         this.Controls.AddRange(new System.Windows.Forms.Control[] {

             this.resultLabel, this.sortButton});

         this.Name = "bubbleSort";

         this.Text = "C# bubble sort";

         this.ResumeLayout(false);

      }



      static void Main()

      {

         Application.Run(new BubbleSorter());

      }



      private void sortButton_Click( object sender, 

            System.EventArgs e )

      {

         int[] ar =  { 22, 6, 4, -7, 13, 12, 89, 68, 37, 44, -15 };

      

         resultLabel.Text = "items in original order\n";



         for ( int i = 0; i < ar.Length; i++ )

            resultLabel.Text += "   " + ar[ i ];



         // sort items of array ar

         BubbleSort( ar );



         resultLabel.Text += "\n\nitems in ascending order\n";



         for ( int i = 0; i < ar.Length; i++ )

            resultLabel.Text += "   " + ar[ i ];



      }



      // sort the items of an array using bubble sort

      public void BubbleSort( int[] ar )

      {

         for ( int pass = 1; pass < ar.Length; pass++ )

            for ( int i = 0; i < ar.Length - 1; i++ )

               if ( ar[ i ] > ar[ i + 1 ] )

                  Swap( ar, i );

      }



      // swap two items of an array

      public void Swap( int[] ar, int first )

      {

         int hold;



         hold = ar[ first ];

         ar[ first ] = ar[ first + 1 ];

         ar[ first + 1 ] = hold;

      }

   }

}

Open in new window

0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
What are the big features of MVC5? 4 50
c# string 6 39
Handling arrays 14 33
Object Oriented Best Practice 5 32
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now