Tuesday, January 10, 2012

Selection Sort

Idea: 
- Select the smallest element and move to the first position of current array
- Consider the number of elements of  the current array is n-1
- Repeat the two above steps until the number of elements of the current array is 1

Algorithm:
- Step 1: Assign i =0
- Step 2: Loop
       + Look for a[min] from a[i] to a[n-1]
       + Swap a[min] and a[i]
- Step 3: Compare i and n
       + If i <=: i + 1, repeat step 2
       + On the contrary: Stop

Implementation
        static void Swap(ref int a, ref int b)
        {
            int c = a;
            a = b;
            b = c;
        }

        static void SelectionSort(int[] a)
        {
            int max;
            for (int i = 0; i < a.Length - 1; i++)
            {                 
                max = i;
                for (int j = i + 1; j < a.Length; j++)
                {                     
                    if (a[j] > a[max])
                    {
                        max = j;
                    }
                }
                 if (max != i)
                {
                    Swap(ref a[max], ref a[i]);
                }
            }           
        }


Hope this help!

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Affiliate Network Reviews