PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 14, 2022

[FIXED] Why am i getting wrong sorting result in Selection sort for specific this input only?

 August 14, 2022     java, output, selection-sort, sorting     No comments   

Issue

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


Solution

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.



Answered By - Bohemian
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing