0

I had to code Selection Sort, and I previously used an Array and it worked perfectly, but the textfiles were too large to use an Array so I had to convert the code to ArrayList. What happens now is, (with the large textfile too) majority numbers are sorted but there are a few unsorted number in between the sorted ones, think it might be a duplication error... I have tried changing to descending order and it does the same thing. I used a smaller textfile to show the output. All the relevant methods are below.

public void SelectionSort() // ascending order
{

    for (int i = 1; i <= List.Count; i++) // go through the list
    {
        ListClass minimum = (ListClass)List[i-1];
        int min = i - 1;
        for (int j = i;j <= List.Count-1; j++)
        {
            ListClass cur = (ListClass)List[j];

            if (minimum.getNum() > cur.getNum())
                min = j; // min equals smallest in list j

        }
        swap(List, i-1, min); 
    }
    Console.WriteLine("Array after selection sort: ");
    foreach (ListClass cur in List)
    {
        cur.Display();
    }
public static void swap(ArrayList List, int x, int y)
{
    object temp = List[x];
    List[x] = List[y];
    List[y] = temp;
}
public void Display()
{
    foreach (ListClass cur in List)
    {
        cur.Display();
    }
}

Array before sorting: 1 2 5 7 8 90 889 88 654 33 2 3 Array after selection sort: 1 2 3 5 7 8 90 2 88 33 654 889

3
  • Why don't you use the List<T>.Sort? Or the Array.Sort? Commented Apr 27, 2019 at 19:41
  • 1
    I think you need to update the 'minimum' variable when you update 'min'. Otherwise you keep comparing with the original value. Commented Apr 27, 2019 at 19:43
  • Don‘t use ArrayLists. They are deprecated since several years now. Not only does List<T> provides sorting, but also type-safety (so you don’t need to cast) and better performance. Commented Apr 27, 2019 at 22:22

1 Answer 1

2

you shouldn't compare the minimum of unsorted part with the last sorted value and swap it with that, you just have to find the minimum of the unsorted part and swap it with the first unsorted value(next to the last sorted value).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.