RSS

Sorting Algorithms

Wed, Jan 20, 2010

Inverview Tips

Overview of many sorting techniques and sample code.

Insertion Sort
If you are asked to do the Insertion sort you can follow the code:

public static int[] InsertionSort(int[] a)
{
	for (int i = 1; i < a.Length; i++)
	{
		int k = i;
		while (a[k] < a[k - 1] && k > 0)
		{
			int temp = a[k];
			a[k] = a[k - 1];
			a[k - 1] = temp;
			k--;
		}
 
	}
	return a;
}

Selection Sort
If you are asked to write Selection Sort you can follow the code:

public static int[] SelectionSort(int[] a)
{
	for (int i = 0; i < a.Length; i++)
	{
		int min = i;
		for (int j = i; j < a.Length; j++)
	  {
		   if (a[min] > a[j])
			{
				min = j;
			}
		}
		if (i != min)
		{
			int temp = a[min];
			a[min] = a[i];
			a[i] = temp;
 
		}
	}
	return a;
 
}

Bubble Sort

public static int[] BubbleSort(int[] a)
{
	for (int i = 0; i < a.Length; i++)
	{
		for (int j = 0; j < a.Length; j++)
		{
			if (a[i] < a[j])
			{
				int temp = a[i];
				a[i] = a[j];
				a[j] = temp;
			}
		}
	}
	return a;        
}
Sharing ~ Helping Other:
  • Print
  • email
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • BlinkList
  • DZone
  • Slashdot
  • YahooMyWeb
  • StumbleUpon
  • Live
  • IndianPad
  • DotNetKicks
  • Technorati

Other Posts:

This post was written by:

Ujwal Manandhar - who has written 4 posts on eXclusiveMinds.


Contact the author

Leave a Reply

You must be logged in to post a comment.