Bubble Sorting string in an array - java

I'm trying to bubble sort string data that was input into an array in descending and ascending order.
The following is the code so far:
import java.util.*;
public class nextLineArray
{
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 initial list
System.out.println("List of names via input:"+ names);
//Print descending order list
String descSort;
descSort=bubbleSortDesc(names);
System.out.println("Names listed sorted in descending order (via BubbleSort): "+descSort);
}
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;
}
}
When I try to return the sorted array to the main method it gives me the following error on the return line:
Incompatible Types
Our online instructor just started us out with using multiple methods and arrays at the same time and it is quite confusing...please excuse me if any of my mistakes appear to be obvious.
Edit: I have fixed the initial problem thanks to Alexandre Santos in the comments, I am now running into a problem when executing the program after inputting the data, instead of printing the strings in the array it prints out
[Ljava.lang.String;#6d782f7c

Take a look at the method
public static String bubbleSortDesc(String[] names)
The return of that method is supposed to be a String (only one), but you are returning the parameter "names", which is an array of strings. The "[]" after the String identifies it as an array.
I am not going to do your homework for you, so a hint: check if the return type of the method bubbleSortDesc should be one String or an array of Strings.
Good luck.

There are 2 points to fix. First you should return String array
public static String[] bubbleSortDesc(String[] names)
and therefore you should define it like this:
String descSort[];

public static String bubbleSortDesc(String[] names)
should be
public static String[] bubbleSortDesc(String[] names)
and also declare descSort as String array.
Also you are just printing the array objects. This will not print the list for you. You have iterate over the array.
Include this in you code:
for (String name:names)
{
System.out.println(name);
}
Do the same for descSort too....

You can fix your print command by changing it to the following:
System.out.println("Names listed sorted in descending order (via BubbleSort): "+ java.util.Arrays.deepToString(descSort));
If you want the nitty gritty, descSort is a String[]. In Java when you convert String[] into a String it gives you that crazy string representation. You have to instead converte each entry in the array to a String individually. Fortunately the deepToString method will do that for you.

Related

How to change an arrays into a String with each name on a separate line in java?

I am a newbie to java and I am trying to begin with a simple task- list a group of names into alphabetical order. Currently, my code is fine:
import java.util.Arrays;
public class CLASSROOM_SSONG {
String[] names = {"Joe", "Bob", "Andy"};
public static void main(String args[]) {
CLASSROOM_SSONG x =new CLASSROOM_SSONG();
x.roster();
}
public String [] roster() {
Arrays.sort(names);
System.out.println(Arrays.toString(names));
return names;
}
}
However, this code returns an ARRAY with the brackets, and I prefer there to be names on separate lines without the brackets. This is what I am looking for it to return:
Andy
Bob
Joe
How would I do that? I thought 'println' would give each a separate line, but now I am stuck. I can't think of a way without having to print each name separately, which defeats the purpose completely.
All help would be appreciated!
Oh, by the way, when I search for answers, sometimes I get crazy things with a ton of helper methods. I Prefer simple ones that I can read :)
The easiest way is to output the names one after the other. This is possible with a simple for-loop or any iterators.
Simple For-loop:
String[] names = {"Joe", "Bob", "Andy"};
for (String name : names) {
System.out.println(name);
}
You need to go through the array and print out each name with:
for(String name: names) {
System.out.println(name);
}
or
for (int i=0; i < names.length; i++){
System.out.println(names[i]);
}
String array;
for(int i=0;i<names.length;++i){
array+=names[i]+"\n";
}
System.out.println(array);
Maybe this is not the best approach!
Try this.
Arrays.sort(names); // sort first
System.out.println(String.join("\n", Arrays.asList(names)));
// Arrays.asList(names) converts the string into an ArrayList
You can use JAVA 8 to sort and print each element on a new line.
import java.util.Arrays;
public class CLASSROOM_SSONG {
String[] names = {"Joe", "Bob", "Andy"};
public static void main(String args[]) {
CLASSROOM_SSONG x =new CLASSROOM_SSONG();
x.roster();
}
public void roster() {
// sort the array and print it to new line
Arrays.stream(names).sorted().forEach(System.out::println);
}
}

How to sort String array by length using Arrays.sort()

I am trying to sort an array of strings according to their length using Arrays.sort(), but this sorts the strings lexicographically rather than by length. Here is my code:
S = "No one could disentangle correctly"
String W[] = S.split(" ");
Arrays.sort(W);
After sorting :
correctly
could
disentangle
no
one
but what I want is
no //length = 2
one //length = 3
could //length = 4 and likewise
correctly
disentangle
How can I get the above output? Please give answer for JDK 1.7 & JDK1.8.
For java 8 and above
Arrays.sort(W, (a, b)->Integer.compare(a.length(), b.length()));
A more concise way is to use Comparator.comparingInt from Mano's answer here.
Alternative to and slightly simpler than matt's version
Arrays.sort(W, Comparator.comparingInt(String::length));
If you are using JDK 1.8 or above then you could use lambda expression like matt answer. But if you are using JDK 1.7 or earlier version try to write a custom Comparator like this:
String S = "No one could disentangle correctly";
String W[] = S.split(" ");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparision
}
});
Simply changing the parameter position we can sort in descending order.
Arrays.sort(W, (a,b)->b.length() - a.length());
Java 8 is pretty easy. as mentioned in the above answer.
I was solving some problems on hackerrank and there they are using java 7. so I had to write the java7.
That is selection sort. though time complexity is not great O(n^2) however it serves the purpose.
public static void main(String[] args) {
// I am taking list and again converting to array. please ignore. you can directly take array of string and apply the logic.
List<String> listOfString = new ArrayList<String>();
listOfString.add("because");
listOfString.add("can");
listOfString.add("do");
listOfString.add("must");
listOfString.add("we");
listOfString.add("what");
String[] w= new String[listOfString.size()];
for(int i =0;i <listOfString.size();i++) {
w[i] = listOfString.get(i);
}
// That is for java 8
//Arrays.sort(w, (a, b)->Integer.compare(a.length(), b.length()));
for (int i = 0; i < w.length; i++) {
for(int j=i+1;j<w.length;j++) {
String tempi = w[i];
String tempj = w[j];
if(tempj.length()<tempi.length()) {
w[i] =w[j];
w[j]=tempi;
}
}
}
// That is for printing the sorted array
for (int i = 0; i < w.length; i++) {
System.out.println(w[i]);
}
Output.
do
we
can
must
what
because
My answer is kind of irrelevant to this question (I wanted to sort and a list not an array) but since the answers provided here helped me solve my error, am going to leave it here for those that are facing the issue had.
Collections.sort(vehicles, (VehiclePayload vp1, VehiclePayload vp2)
-> Integer.compare(vp2.getPlateNumber().length(), vp1.getPlateNumber().length()));
If you prefer Streams in Java8 onwards then you could use -
String input = "This is a beautiful world";
String[] arr = Arrays.stream(input.split(" "))
.sorted(Comparator.comparingInt(String::length))
.toArray(String[]::new);
// prints output
System.out.println(Arrays.toString(arr));
The output is -
[a, is, This, world, beautiful]
import java.util.*;
class SortStringArray
{
public static void main (String[] args) throws java.lang.Exception
{
String S = "No one could disentangle correctly";
String W[] = S.split(" ");
Arrays.sort(W, new StringLengthComparator());
for(String str: W)
System.out.println(str); //print Your Expected Result.
}
}
class StringLengthComparator implements Comparator<String>{ //Custom Comparator class according to your need
#Override
public int compare(String str1, String str2) {
return str1.length() - str2.length();// compare length of Strings
}
}
//possible but not recommended;
String sp[]="No one could disentangle correctly".split(" ");
for(int i=0;i<sp.length-1;i++)
{
for(int j=i+1;j<sp.length;j++)
{
if(sp[i].length()>sp[j].length())
{
String temp=sp[i];
sp[i]=sp[j];
sp[j]=temp;
}
}
}
for(String i:sp) //will print content of array sp
System.out.println(i);
ArrayList<String> list=new ArrayList<>();
list.add("diamond");
list.add("silver");
list.add("gold");
System.out.println(list.stream().sorted(Comparator.comparingInt(String::length)).collect(Collectors.toList()));
output:
[gold, silver, diamond]

How do i sort an array of strings by the second char of each string?

I wrote a program that asks users to input names into an array and then the names are sorted in alphabetical order...The program works good but I was wondering if I could sort each of the names entered by the 2nd, 3rd, or 4th character in each string? For example, if the user entered Bob, Dan, and Kris the program should sort them as Dan, Bob, Kris. This is my program that sorts my array of strings by the first letter of the string:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class SortingAnArrayOfStrings {
public static void main(String[] args) {
{
//Ask the user for names to add to the array
List<String> list=new ArrayList<String>();
Scanner in=new Scanner(System.in);
do {
System.out.println(" The names on the list are "+list);
System.out.println("Would you like to add another name to the list? (y/n)");
if (in.next().startsWith("y")) {
System.out.println("Enter:");
list.add(in.next());
}else{break;
}
} while (true);
//display the names that have been added to the array
System.out.println("The names on the list are "+list);
//sort the array of names in alphabetical order
String[] Arr=list.toArray(new String[list.size()]);
String[] stringArray=new String[Arr.length];
for(int i=0;i<Arr.length;i++)
{
for (int j = i+1; j < Arr.length; j++) {
if (Arr[i].trim().compareTo(Arr[j].trim())>0) {
String temp=Arr[j];
Arr[j]=Arr[i];
Arr[i]=temp;
}
}
stringArray[i]=Arr[i];
}
//display the sorted list of names
System.out.println("This is the list of names after sorting them in alphabetical order : ");
for(String ss:stringArray){
System.out.print(ss + " ");
}
}
}
}
You could try something like bellow using a custom java.util.Comparator:
String[] names = {"Dan", "Bob", "Kris"};
java.util.Collections.sort(java.util.Arrays.asList(names), new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.charAt(1) - s2.charAt(1);//comparision
}
});
for (String name : names) System.out.println(name);
output:
Dan
Bob
Kris
You could try this, just add a custom comparator by using Lambda expressions if you are using java version 1.8 or above :
list.add("Bob");
list.add("Dan");
list.add("Kris");
Collections.sort(list, (s1, s2) -> {
String sb1 = s1.substring(1);
String sb2 = s2.substring(1);
return sb1.compareTo(sb2);
});
System.out.println("list = " + list);
The Result:
list = [Dan, Bob, Kris]
I haven't tested this one but you could try this one. Replace the condition part of your code by this one.
Though, there may be some performance issue.
if (Arr[i].trim().compareTo(Arr[j].trim())>0) {
Replace with:
if (Arr[i].trim().charAt(nthChar) > Arr[j].trim().charAt(nthChar)) {
The nthChar is the character placement to compare.
Here is sample tested code. You need to use comparator so as to implement the order.
Here value of order can be anything based on your requirement. You can replace your current code with this because it is fine for normal sorting as well (based on index 0). It might require some tweaks based on your need.
String str[] = {"abc","bca","avc","ert"};
final int ORDER = 1;
Arrays.sort(str, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o1.toLowerCase().charAt(ORDER) - o2.toLowerCase().charAt(ORDER) ;
}
});
Add different implementations of java.util.Comparator based on the requirement and use
public static <T> void sort(List<T> list,
Comparator<? super T> c) in collections class to sort the list.
You want to use a custom comparator.

Moving indices in an array

I am trying to write a write a program that receives an String[] and prints out the array with the first string alphabetically first. I have to use three methods like these. Here is a sample input/output:
bob, joe, aaron, zack ----> aaron, bob, joe, zack
findFirstName() is correctly finding the first String alphabetically and returning its location.
MoveToRightOne is correctly shifting each String right one while overwriting the first string alphabetically and repeating the first one (ex: bob bob joe zack).
moveName() is not working correctly. It is supposed to replace the first instance of "bob" with "aaron" but is usually off by one or two places.
Does anyone see why this might be happening in moveOne()?
public static String [] moveName(String [] names) {
String names1 [] = names.clone();
int firstPosition = findFirstName(names1);
String[] NewNames = moveToRightOne(names1, firstPosition, firstPosition+1);
String firstAlph= names1 [firstPosition];
System.out.println(names1 [firstPosition]);
NewNames [0] = firstAlph;
return NewNames;
}
public static int findFirstName(String[ ] names1 ) {
// receives an array of Strings, and returns the location (i.e. index) of the first
// name (alphabetically)
String first=names1[0];
int firstPosition = 0;
for (int i=0; i<names1.length; i++) {
int result =names1[i].compareToIgnoreCase(first);
if (result < 0) {
first= names1[i];
firstPosition = i;
}
}
return firstPosition;
}
public static String[] moveToRightOne (String[] names, int startSpot, int endSpot) {
for (int i = (startSpot - 1); i >= 0; i--) {
names[i+1] = names[i];
}
return names;
}
moveToRightOne does not make a copy of the names array that you pass in. Instead, it modifies it directly. That means when you say
String[] NewNames = moveToRightOne(names1, firstPosition, firstPosition+1);
the strings will be shifted in names1, and after that, NewNames and names1 will just be references to the same array. I think your intent is to make NewNames be an array with the strings shifted, and leave names1 alone, but that isn't what's happening. That means that the following statement is going to return the wrong string:
String firstAlph= names1 [firstPosition];
(Or, since names1 is already a clone of names, maybe what you want is to use names instead of names1 when trying to access elements from the not-yet-shifted array.)
Your moveToRightOne function was broken, so you were not actually using all the parameters passed in. Also, you should grab the first name alphabetically before you actually overwrite it using that function.
public class Shift {
public static void moveName(String [] names) {
int firstPosition = findFirstName(names);
// Store the name at that position
String firstName = names[firstPosition];
moveToRightOne(names, 0, firstPosition);
names [0] = firstName;
}
public static int findFirstName(String[] names1) {
// receives an array of Strings, and returns the location (i.e. index)
// of the first name (alphabetically)
String first=names1[0];
int firstPosition = 0;
for (int i=0; i<names1.length; i++) {
int result =names1[i].compareToIgnoreCase(first);
if (result < 0) {
first= names1[i];
firstPosition = i;
}
}
return firstPosition;
}
public static void moveToRightOne (String[] names, int startSpot, int endSpot) {
for (int i = (endSpot - 1); i >= startSpot; i--) {
names[i+1] = names[i];
}
}
public static void main(String[] args) {
String[] original = new String[] { "bob", "joe", "aaron", "zac"};
for (String s: original) System.out.println(s);
System.out.println();
moveName(original);
for (String s: original) System.out.println(s);
}
}
Are you sure the moveToRightOne is correct? (if firstPosition is 0 you will get no changes as the for loop will not execute)
Just a quick Thought:
If you are looking do a sort manually (I assume this is for a class). I will also assume you are trying to implement insertion sort algorithm (otherwise Arrays.sort() is your friend). The way you are approaching it, it looks like you will be making multiple passes through the array to achieve a sort. if you want to do that switch to bubble sort instead.
The description of the insertion sort code will look something like this:
Start looping through your array, compare that the element at index is greater than element at index + 1. if not true move to the next element. if true compare the smaller element (call it A) to all previous elements until it is greater than the next previous element (lets call it B). Save a copy of A Shift all elements after B to the right (by 1) until you get to the A's old position . insert the copy of A into position just after B. Continue from the old A's index. Rinse/repeat until the end of the array
you may want to simplify your code in that case (and always check for edge conditions like 0 and Array.length)
HTH
Please use Arrays.sort() for sorting instead.This is not exact solution for the problem, but an alternate way for it.
import java.util.Arrays;
public class Test{
Public static void main(String args[]){
String str[]= {'Mike','Adam','Peter','Brian'};
System.out.println("str"+str[0]); // Mike
Arrays.sort(str);
System.out.println("str"+str[0]); //Adam
}
}

Printing content of an Array in Java

This generates the array.
public word (String file)
{...
public int[] getArray()
{
int[] array = {... } ;
return array;
}
}
And I need to reference that array in another class
public static void main()
{
word numarray = new word("doc.txt");
int [] heightarray = numarray.getArray();
System.out.println(heightarray);
}
I'm not getting any errors but I get things like [I#1a6fa30c as a result.
What you are getting in the output is the hashcode of the array. In order to print the contents of the array you can you either of the below options :
Option 1 : Print the elements one by one using a loop a below :
for(int val : heightarray)
{
System.out.print(val + ",");
}
Option 2 : Use Arrays utility class for printing the array
System.out.println(Arrays.toString(heightarray));
You can print it using the Arrays.toString() method:
System.out.println(Arrays.toString(heightarray));

Categories

Resources