Skip to content

Selection problem !!!

pRoGi

Asked Jan 17, 2006, 5:05 AM EST1 answer
Share
LinkedInX

Hi. I have this code:

using System;

class Selection
{
  public static void SelectionSort(ref int[] T)
  {
 int min = 0, i, j, pom;
 for (i = 0; i < (T.Length-1); i++)
 {
   min = i;
   for (j = i + 1; j < T.Length; j++)
   {
  if (T[j] < T[min])
    min = j;
   }
   pom = T[i];
   T[i] = T[min];
   T[min] = pom;
 }
  }
  public static void InsertionSort(ref int[] T)
  {
 int j, pom;
 for (int i = 1; i < T.Length; i++)
 {
   j = i;
   pom = T[i];
   while (T[j-1] > pom)
   {
  T[j] = T[j-1];
  j = j-1;
   }
   T[j] = pom;
 }
  }
  public static void BubbelSort(ref int[] T)
  {
 int pom;
 for (int i = 1; i < T.Length; i++)
   for (int j = T.Length; j > i; j--)
  if (T[j-1] > T[j])
  {
    pom = T[j-1];
    T[j-1] = T[j];
    T[j] = pom;
  }
  }


  public static void Main()
  {
 Console.Write("Podaj liczbe el. tablicy: ");
 int n = Int32.Parse(Console.ReadLine());
 int[] tab = new int[n];
 Random rnd = new Random();
 for (int i = 0; i < tab.Length; i++)
 {
   tab[i] = rnd.Next(10);
   Console.WriteLine(tab[i]);
 }
 Console.WriteLine();
 BubbelSort(ref tab);
 for (int i = 0; i < tab.Length; i++)
 Console.WriteLine(tab[i]);
 Console.ReadLine();
  }
}

And when i am using BubbelSort and InsertionSort program shows exception System.IndexOutOfRangeException, and my question sounds why ?? (SelectionSort works good)

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0

    Because the algorithms are written wrong...? ;)

    Here's the simplest bubbler:

    Python
    void BubbleSort(int[] 
    items)
    
    {
    
        for 
    (int pass = 
    1; pass < items.Length; 
    pass++)
    
        {
    
            
    for (int 
    i = 0; i < 
    items.Length - pass; i++)
    
            {
    
                
    if (items[i] > items[i +
    1])
    
                {
    
                   
    // swap
    
                   
    int temp = items[i];
    
                    
    items[i] = items[i + 1];
    
                    
    items[i + 1] = temp;
    
                }
    
            }
    
        }
    
    }

    Try to search for good sorting algorithms for example in C++ language, there's plenty of them in the internet, and they are easy to convert to C# too. My example was converted from this: http://www.fredosaurus.com/notes-cpp/algorithms/sorting/bubblesort-fixed.html

    0