Hi all,
my code provide requested results but verification always failed.
Any suggestion?
At first I got only one isGreaterThan method and use commented out code, then I tried to add another isGreaterThan method.
I would really appreciate some help :)
package com.codegym.task.task09.task0930;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
/*
Task about algorithms
*/
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
ArrayList<String> list = new ArrayList<String>();
while (true) {
String s = reader.readLine();
if (s.isEmpty()) break;
list.add(s);
}
String[] array = list.toArray(new String[list.size()]);
sort(array);
for (String x : array) {
System.out.println(x);
}
}
public static void sort(String[] array) {
// write your code here
//prepare list of positions
ArrayList<Integer> list_string_positions = new ArrayList<>();
ArrayList<Integer> list_int_positions = new ArrayList<>();
int i_position = 0;
for(String s: array){
//System.out.println(isNumber(s));
if ( isNumber(s) )
list_int_positions.add(i_position);
else{
list_string_positions.add(i_position);
}
i_position++;
}
// sort strings
int b=list_int_positions.size();
String temp1;
for(int i=0;i<b;i++)
{
for (int j = i + 1; j < b; j++)
{
if ( isGreaterThan( array[ list_string_positions.get(i) ], array[ list_string_positions.get(j) ] ) ){
temp1 = array[ list_string_positions.get(i) ];
array[ list_string_positions.get(i) ] = array[ list_string_positions.get(j) ];
array[ list_string_positions.get(j) ] = temp1;
}
}
}
// sort nubmers
int n=list_int_positions.size();
String temp;
for(int i=0;i<n;i++)
{
for (int j = i + 1; j < n; j++)
{
//if ( Integer.valueOf( array[ list_int_positions.get(i) ] ) < Integer.valueOf( array[ list_int_positions.get(j) ] ) ){
if ( isGreaterThan( Integer.valueOf( array[ list_int_positions.get(i) ] ) ,Integer.valueOf( array[ list_int_positions.get(j) ] ) ) ){
temp1 = array[ list_int_positions.get(i) ];
array[ list_int_positions.get(i) ] = array[ list_int_positions.get(j) ];
array[ list_int_positions.get(j) ] = temp1;
}
}
}
}
// String comparison method: 'a' is greater than 'b'
public static boolean isGreaterThan(String a, String b) {
return a.compareTo(b) > 0;
}
public static boolean isGreaterThan(int a, int b) {
return a < b;
}
// Is the passed string a number?
public static boolean isNumber(String s) {
if (s.length() == 0) return false;
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if ((i != 0 && c == '-') // The string contains a hyphen
|| (!Character.isDigit(c) && c != '-') // or is not a number and doesn't start with a hyphen
|| (i == 0 && c == '-' && chars.length == 1)) // or is a single hyphen
{
return false;
}
}
return true;
}
}