Home > front end >  Why am i getting wrong sorting result in Selection sort for specific this input only?
Why am i getting wrong sorting result in Selection sort for specific this input only?

Time:06-05

What wrong am I doing in this sort? I'm getting the wrong output for this input only.

public class SelectionSort {
  public void sort (int nums[]){
    for(int i = 0; i < nums.length - 1; i   ){
      int min_index = i;
      for(int j = i   1; j < nums.length; j   ){
        if(nums[j] < nums[min_index]){
          min_index = j;

          int temp = nums[min_index];
          nums[min_index] = nums[i];
          nums[i] = temp;
        }
      }
    }
  }
  public void printArr(int nums[]){
    for(int i = 0; i < nums.length;   i){
      System.out.println(nums[i]);
    }
  }
  public static void main(String args[]){
    int nums[] = {10,22,34, 45, 50, 60, 8, 12};
    SelectionSort obj = new SelectionSort();
    obj.sort(nums);
    obj.printArr(nums);
  }
}

Wrong Output 8 12 10 22 34 45 50 60

Correct Output should be 8 10 12 22 34 45 50 60

CodePudding user response:

You're swapping every time you find a new minimum:

if(nums[j] < nums[min_index]){
    min_index = j;

    int temp = nums[min_index];
    nums[min_index] = nums[i];
    nums[i] = temp;
}

Instead, swap only when you've found the lowest minimum: Move the swap after the j loop.


Learning how to debug code is an essential skill. Java was designed to support debugging. Use an IDE (I recommend IntelliJ) and learn how to use its debugger.

  • Related