java - Why my selection sort doesn't sort at all? -
i trying run selection sort see how work , apparently, code have doesnt work expected, can help me point out did wrong? know thing goes wrong @ swapping part, not sure why.
public class sortingalgorithm { private long timerun; public sortingalgorithm() { timerun = 0; } public long gettimerun() { homecoming 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; homecoming arr; } }
here 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 array for(int counter = 0; counter < length ;counter++) { arr[counter] = rand.nextint(10); } sortingalgorithm tool = new sortingalgorithm(); arr = tool.selection(arr, length); for(int = 0; < length ;i++) { system.out.println(arr[i]); } system.out.println(tool.gettimerun()); } }
when phone call swap, pass in array elements:
swap(arr[i], arr[k], arr); but function expects indexes array. should invoking this:
swap(i, k, arr); java sorting selection-sort
No comments:
Post a Comment