Search code examples
javasortingselection-sort

Why my selection sort doesn't sort at all?


I am trying to run selection sort to see how it work and apparently, the code that I have doesnt work as expected, can someone help me point out what i did wrong? I know the thing goes wrong at swapping part, but i am not sure why.

public class SortingAlgorithm
{
private long timeRun;

public SortingAlgorithm()
{
    timeRun = 0;
}

public long getTimeRun() 
{
    return timeRun;
}

public void setTimeRun(long timeRun) 
{
    this.timeRun = timeRun;
}

private void swap(int a, int b, int[] arrB)
{
    int temp = arrB[a];
    arrB[a] = arrB[b];
    arrB[b] = temp;
}
public int[] selection(int[] arr, int length)
{
    long startTime = System.nanoTime();
    for(int i= 0; i<length-1; i++)
    {
        for(int k = i+1; k<length; k++)
        {
            if(arr[i] > arr[k])
            {
                swap(arr[i], arr[k], arr);
            }
        }
    }
    timeRun = System.nanoTime() - startTime;
    return arr;

}

}

Here is the driver:

import java.util.*;
public class Driver 
{
        private static int length = 10;
        private static int[] arr = new int [length];
        public static void main(String [] args)
{
    Random rand = new Random();
    //seed the array
    for(int counter = 0; counter < length ;counter++)
    {
        arr[counter] = rand.nextInt(10);
    }

    SortingAlgorithm tool = new SortingAlgorithm();
    arr = tool.selection(arr, length);

    for(int i = 0; i < length ;i++)
    {
        System.out.println(arr[i]);
    }

    System.out.println(tool.getTimeRun());
}

}


Solution

  • When you call swap, you pass in array elements:

    swap(arr[i], arr[k], arr);
    

    But your function expects the indexes to the array. You should be invoking it like this:

    swap(i, k, arr);