I've run into trouble when sorting string in an array.
I'm supposed to get two different outputs from my code, but I only get the output in ascending order.
import java.util.*;
public class nextLineArray1
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String names[]=new String[12];
System.out.println("Enter the 12 names: ");
//Load Array
for(int i = 0; i < 12; i++)
{
names[i] = input.nextLine();
}
//Print descending order list
String[] descSort;
descSort=bubbleSortDesc(names);
System.out.println("Names listed sorted in descending order (via BubbleSort): ");
for(int x=0; x < names.length; x++)
{
System.out.println(names[x]);
}
//Print ascending order list
String[] ascSort;
ascSort=bubbleSortAsc(names);
System.out.println("Names listed sorted in ascending order (via BubbleSort): ");
for(int z=0; z < names.length; z++)
{
System.out.println(names[z]);
}
}
public static String[] bubbleSortDesc(String[] names)
{
String temp;
int passNum, i, result;
for(passNum=1; passNum <= 11; passNum++)
{
for(i = 0; i<=(11-passNum); i++)
{
result=names[i].compareToIgnoreCase(names[i+1]);
if(result>0)
{
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
public static String[] bubbleSortAsc(String[] names)
{
String temp;
int passNum, i, result;
for(passNum=1; passNum <= 11; passNum++)
{
for(i = 0; i<=(11-passNum); i++)
{
result=names[i].compareToIgnoreCase(names[i]);
if(result>0)
{
temp=names[i-1];
names[i-1]=names[i];
names[i]=temp;
}
}
}
return names;
}
}
An explanation of why it is only sorting in ascending order, would be more than helpful.
Thanks in advance.