Reputation: 25
I have to sort a string of names in descending order in bubble sort. I tried but it is not working. This is what I have so far:
public static void bubbleSort(Student[] array)
{
for(int i=(array.length); i>0; i--)
{
for(int j=1; j<(array.length-i); j++)
{
if( array[j].getName().compareTo(array[j+1].getName())<0)
{
Student Temp = array[j];
array[j] = array[j+1];
array[j+1] = Temp;
}
}
}
}
Upvotes: 1
Views: 8090
Reputation: 1
I'm eight years and a month late, but for anyone with the same problem now, here's the solution code:
import java.util.Scanner;
public class sort
{
public static void main(String args[])
{
Scanner scnr=new Scanner(System.in);
String arr[]= new String[20];
System.out.println("Enter names:");
for(int i=0; i<20; i++)
{
arr[i]= scnr.nextLine();
}
String temp; int i;
for(int j=0; j<arr.length;j++)
{
for(i=j+1; i<arr.length; i++)
{
//comparing adjacent string
if(arr[i].compareTo(arr[j]) > 0)
{
temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
System.out.println(arr[j]);
}
}
}
Upvotes: 0
Reputation: 172448
Try this logic
import java.util.*;
public class BubbleSort {
public static void main(String[] args) {
String l[]={"ABCD" , "XYZ" , "DEF" , "PQR"};
BubbleSort(l);
for(int i=0; i<l.length; i++)
{
System.out.println(l[i]);
}
}
private static void BubbleSort(String[] array) {
String t;
for(int i=0; i<array.length; i++) {
for(int j=0; j<array.length-1-i; j++) {
if(array[j].compareTo(array[j+1])>0) {
t= array[j];
array[j] = array[j+1];
array[j+1] = t;
}
}
}
}
}
Upvotes: 2