Don't know why selection sort isn't working?

  • Thread starter Thread starter 1/2"
  • Start date Start date
  • Tags Tags
    Sort
Click For Summary
SUMMARY

The forum discussion centers on a Java implementation of the selection sort algorithm intended to sort an array of names alphabetically. The provided code contains a logical error in the inner loop's comparison, which leads to incorrect sorting results. Specifically, the outer loop iterates incorrectly, and the comparison logic should ensure that the minimum index is updated properly. The user is advised to review the loop boundaries and the comparison conditions to achieve the desired output.

PREREQUISITES
  • Java programming fundamentals
  • Understanding of sorting algorithms, specifically selection sort
  • String comparison methods in Java
  • Basic debugging techniques in Java
NEXT STEPS
  • Review Java's String.compareTo() method for accurate string comparisons
  • Learn about loop control structures in Java to avoid off-by-one errors
  • Explore debugging techniques in Java to identify logical errors in code
  • Study the implementation of other sorting algorithms, such as bubble sort and quicksort
USEFUL FOR

Java developers, computer science students, and anyone learning about sorting algorithms and debugging Java code.

1/2"
Messages
98
Reaction score
0

Homework Statement



to accept 10 names and print alphabetically

Homework Equations





The Attempt at a Solution



public class n1_s
{void main(){
int min,c,q;String t;
String n[]={"b","k","a","w","e"};

for(int i=0;i<4;i++)
{min=i;

for(int j=i+1;j<5;j++)
{

System.out.println(" j starting with ="+j+" n[j]="+n[j]+" n="+n+" n.compareTo(n[j]) = "+n.compareTo(n[j]));
// int a=;
if(n.compareTo(n[j])>0)
{ min=j;

}

}
System.out.println(" exchanged s");
System.out.println(" n["+min+"]/min ="+n[min]+" n["+i+"]="+n);
t=n;
n=n[min];
n[min]=t;
System.out.println(" exchanged");
System.out.println("The new array after exchange ");
for(int f=0;f<5;f++)
{

System.out.print(n[f]+" ");



}
System.out.println();
}
System.out.println(" ");
System.out.println(" Result: ");
for(int y=0;y<5;y++)
{

System.out.println(n[y]);



}

}}
Please point out my mistake .
Thank you
 
Physics news on Phys.org
You might want to show us your output. Otherwise how do we actually know it's incorrect? (Maybe the flaw is in your alphabetical prowess. :biggrin:)

Also, put your code within a [ CODE ] block, to preserve the indenting.
 

Similar threads

  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 18 ·
Replies
18
Views
3K
  • · Replies 7 ·
Replies
7
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 6 ·
Replies
6
Views
2K
  • · Replies 1 ·
Replies
1
Views
1K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K