Avoid printing the last comma - java

I'm trying to print this loop without the last comma. I've been Googling about this and from what i've seen everything seems overcomplex for such a small problem. Surely there is an easy solution to avoid printing the last comma. Much appreciated if somebody could help me out, this is driving me insane!!!
For example it loops from 1-10 // 1,2,3,4,5,6,7,8,9,10, < do not want this last comma
public static void atob(int a,int b)
{
for(int i = a; i <= + b; i++)
{
System.out.print(i + ",");
}
}

I might get stoned to death for this answer
public static void atob(int a,int b) {
if(a<=b) {
System.out.println(a);
for(int i = a+1;i<=b;i++) {
System.out.println(","+i);
}
}
}
}

Yet another way to do this.
String sep = "";
for(int i = a; i <= b; i++) {
System.out.print(sep + i);
sep = ",";
}
if you are using a StringBuilder
StringBuilder sb = new StringBuilder();
for(int i = a; i <= b; i++)
sb.append(i).append(',');
System.out.println(sb.subString(0, sb.length()-1));

Try this
public static void atob(int a,int b)
{
for(int i = a; i < b; i++)
{
System.out.print(i + ",");
}
System.out.print(b);
}

Java 8:
IntStream.rangeClosed(a, b)
.collect(Collectors.joining(","));
If you want to perform interleaving actions:
Java 8:
IntStream.rangeClosed(a, b)
.peek(System.out::print)
.limit(b - a) // [a:(b-1)]
.forEach(i -> System.out.print(","));
Java 9:
IntStream.rangeClosed(a, b)
.peek(System.out::print)
.takeWhile(i -> i < b) // [a:(b-1)]
.forEach(i -> System.out.print(","));

public static void atob(int a, int b) {
if (a < b) {
System.out.print(a);
while (a < b) {
a++;
System.out.print("," + a);
}
}
}
When called with
atob(0,10);
Will give the output
0,1,2,3,4,5,6,7,8,9,10

A general approach could be to make a distinction between the first item and all the others. The first run, no comma is printed BEFORE i. After that, a comma is printed before i, every time.
public static void atob(int a,int b) {
boolean first = true;
for(int i = a; i <= + b; i++) {
if ( first == false ) System.out.print(",");
System.out.print(i);
first = false;
}
}
In this specific case, using the ternary operator (http://en.wikipedia.org/wiki/Ternary_operation), you could write it as compact as:
public static void atob(int a,int b) {
for(int i = a; i <= + b; i++) {
System.out.print( i + ( i < b ? "," : "" ) );
}
}
Without ternary operation, this would look like this (and is more readable, which is often a good thing):
public static void atob(int a,int b) {
for(int i = a; i <= + b; i++) {
System.out.print( i );
if ( i < b ) System.out.print( "," );
}
}
(note that + b is the same as b, so you could replace that, as others have done in their answers)

With slight adjustments (method name, variables, and space after comma):
public static void printSequence(int start, int end) {
if (end < start) {
return; // or however you want to handle this case
}
if (end == start) {
System.out.print(start);
return;
}
StringBuilder sequence = new StringBuilder();
for (int i = start; i <= end; i++) {
sequence.append(i).append(", ");
}
// now simply print the sequence without the last ", "
System.out.print(sequence.substring(0, sequence.length() - 2));
}

Try:
public static void atob(int a, int b) {
if (b < a) {
final int temp = a;
a = b;
b = temp;
}
System.out.print(a++);
for (int i = a; i < b ; i ++ ) {
System.out.print("," + i);
}
}

Use StringBuilder for it. use substring based index.
public class arraySort {
public static void main(String[] args) {
int a[] = { 2, 7, 5, 6, 9, 8, 4, 3, 1 };
for (int i = 0; i < a.length; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[i] < a[j]) {
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.print("Descending order:{");
StringBuilder br = new StringBuilder();
for (int i = 0; i < a.length; i++) {
br.append(a[i] + ",");
}
System.out.print( br.substring(0, br.length()-1));
System.out.println("}");
}
}

public static void atob (int a,int b){
for(int i = a; i <= b; i++)
{
System.out.print(i );
if(i<b){
System.out.print(",");
}
}
}

Clunky solution, but hey - it works.
public static void atob(int a, int b){
int count = 1;
for(int i = a; i <= + b; i++) {
System.out.print(i);
if(count!=((b + 1) - a)) {
System.out.print(", ");
count++;
}
}
}
Alternatively, this works too.
public static void atob(int a, int b){
int count = 0;
for(int i = a; i <= + b; i++) {
if(count > 0){
System.out.print(", ");
}
System.out.print(i);
count++;
}
}

Found another simple way using regex:
String str = "abc, xyz, 123, ";
str = str.replaceAll(", $", "");
System.out.println(str); // "abc, xyz, 123"

You can simply use escape sequence for backspace(\b),outside the main loop,it will delete the last comma.
public static void atob(int a,int b)
{
for(int i = a; i <= + b; i++)
{
System.out.print(i + ",");
}
System.out.print("\b");
}

Related

Rolling hash: my codes fails with modulo for long string

I'm trying to solve https://leetcode.com/problems/longest-repeating-substring/
I want to use rolling hash to match strings.
However, my codes don't seem to work when I deal with modulo.
For a string with all same characters, the maximum length of repeating substring should be string.length - 1.
public class Main {
public static void main(String[] args) {
String str = "bbbbbbbbbbbbbbbbbbb";
System.out.println(str.length() - 1);
Solution s = new Solution();
System.out.println(s.longestRepeatingSubstring(str));
}
}
class Solution {
public int longestRepeatingSubstring(String S) {
HashSet<Long> h = new HashSet();
long mod = (long)1e7 + 7;
for(int i = S.length() - 1; i >0; i--){
h = new HashSet();
long c = 0;
int j = 0;
for(; j < i; j ++){
c = (c*26 % mod + S.charAt(j) - 'a')% mod;
}
h.add(c);
for(; j < S.length(); j++){
c -= (S.charAt(j - i ) - 'a') * Math.pow(26,i-1)% mod;
c = (c*26 % mod + S.charAt(j) - 'a')% mod;
if(h.contains(c)){
return i;
}
h.add(c);
}
}
return 0;
}
}
Playground for my codes: https://leetcode.com/playground/F4HkxbFQ
We cannot see your original link, we need a password.
The usage of modulo seems to be really complex.
Why not try something like this
class Scratch {
// "static void main" must be defined in a public class.
public static void main(String[] args) {
String str = "bbaaabbbbccbbbbbbzzzbbbbb";
System.out.println(str.length() - 1);
Solution s = new Solution();
System.out.println(s.longestRepeatingSubstring(str));
}
static class Solution {
public int longestRepeatingSubstring(String s) {
int max = -1;
int currentLength = 1;
char[] array = s.toCharArray();
for (int index = 1; index < array.length; index++) {
if (array[index - 1] == array[index]) {
currentLength++;
max = Math.max(max, currentLength);
} else {
currentLength = 1;
}
}
return max;
}
}
}

Alternating characters of two different inputs

I want to take two strings and alternate the characters into a new string using a for method.
Example: "two" and "one"
Result: "townoe"
This is what I have so far, and I really don't know how to finish it.
public class Alternator {
String alternate(String a, String b) {
String s = "";
for (int i = 0; i < a.length(); i++) {
s += i;
System.out.println(s);
}
return null;
}
}
public class Alternator{
public static String alternate(String a, String b){
String s = "";
int i = 0;
while (i < a.length() && i < b.length()){
s += a.charAt(i) +""+ b.charAt(i);
i++;
}
while (i < a.length() ){
s += a.charAt(i);
i++;
}
while (i < b.length()){
s += b.charAt(i);
i++;
}
return s;
}
public static void main(String[] args){
String a = "two", b = "one";
String s = Alternator.alternate(a,b);
System.out.println(s);
}
}
To use for loop instead of while loop, simply remove all while lines with for lines like the following, then remove the i++ line from each while loop
for(; i < a.length() && i < b.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
for(; i < a.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
for(; i < b.length(); i++){
//the inside of the loop MINUS THE LINE i++
}
Here is some compact way of doing that:
String alternate(String a, String b) {
StringBuilder builder = new StringBuilder();
int smallerStringLength = Math.min(a.length(), b.length());
for (int i = 0; i < smallerStringLength; i++) {
builder.append(a.charAt(i));
builder.append(b.charAt(i));
}
return builder.toString();
}
Or even more optimized:
String alternate(String first, String second) {
char[] firstChars = first.toCharArray();
char[] secondChars = second.toCharArray();
int smallerCharsCount = Math.min(firstChars.length, secondChars.length);
StringBuilder builder = new StringBuilder(smallerCharsCount * 2);
for (int i = 0; i < smallerCharsCount; i++) {
builder.append(firstChars[i]);
builder.append(secondChars[i]);
}
return builder.toString();
}
This will work if string are of same length or of the different lengths.
static void mergeStrings(String a, String b) {
StringBuilder mergedBuilder = new StringBuilder();
char[] aCharArr = a.toCharArray();
char[] bCharArr = b.toCharArray();
int minLength = aCharArr.length >= bCharArr.length ? bCharArr.length : aCharArr.length;
for (int i=0; i<minLength; i++) {
mergedBuilder.append(aCharArr[i]).append(bCharArr[i]);
}
if(minLength < aCharArr.length) {
mergedBuilder.append(a.substring(minLength));
}
else{
mergedBuilder.append(b.substring(minLength));
}
Systemout.println(mergedBuilder.toString());
}
Assuming that the two strings are the exact same length, you can do the following. If they are different length, then currently your prompt doesn't say how you want the resultant string to be set up.
public class Alternator {
String alternate(String a, String b) {
String s = "";
for (int i = 0; i < 2*a.length(); i++) {
if (i%2==0) // modular arithmetic to alternate
s += a.charAt(i/2); // Note the integer division
else
s += b.charAt(i/2);
}
System.out.println(s);
return s;
}
}
Alternatively, even easier, but the index i doesn't mark the length of your string s:
public class Alternator {
String alternate(String a, String b) {
String s = "";
for(int i = 0; i < a.length(); i++){
s += a.charAt(i);
s += b.charAt(i);
}
return s;
}
}
Use this:
String alternate(String a, String b){
StringBuilder builder = new StringBuilder();
final int greaterLength = a.length() > b.length() ? a.length() : b.length();
for(int i = 0; i < greaterLength; i++){
if (i < a.length()) {
builder.append(a.charAt(i));
}
if (i < b.length()) {
builder.append(b.charAt(i));
}
}
return builder.toString();
}
It uses the String.charAt method to obtain letters, and a StringBuilder to create the string.
(When given two strings of non-equal length, this returns an alternation of the first two chars, and then does just the remaining string. EG: Hello and Hi --> HHeillo)
According to the comments I've read, you are having trouble understanding for loops, and how to use them with strings.
For loops are most often used to iterate over arrays, or to perform a task a given number of times.
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
This would give the output
0
1
2
3
4
For loops start at the value of the initializer, the first thing you put in int i = 0;
They then check the expression, the second part of the for loop, and if it returns true, it executes all of the code inside the braces. i < 5;
Once it has done that, it runs the incrementor, the last part of the for loop. i++
After that, it checks the expression again. I guess you can see where this is going. Until the expression returns false, everything inside the curly braces of the for loop gets executed over and over again.
Strings can be iterated over with a for loop, but you can't reference it like an array using array[index]. You have to either convert it into an array, using .toCharArray() on your String, and return the result to an empty char array char[], or use the .charAt(index) method on your string.
This code will go over a string, and output each character, one by one:
for (int i = 0; i < myString.length(); i++) {
System.out.println(myString.charAt(i));
}
If the string had a value of "Hello", the output would be:
H
e
l
l
o
Using this, instead of outputting the characters using System.out.println();, we can put them into an empty string, using +=:
myOtherString += myString.charAt(i);
That means, if we want to go over two Strings at a time, and alternate them, like you do, we can iterate over two strings at the same time, and add them to a new string:
myAlternatedString += myString.charAt(i);
myAlternatedString += myOtherString.charAt(i);
if MyString was still "Hello" and myOtherString was "World", the new string would be:
Hweolrllod
following code reads 2 different inputs and merges into a single string.
public class PrintAlternnateCharacterString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String a = in.next();
String b = in.next();
String mergedString = "";
int lenA = a.length();
int lenB = b.length();
if (lenA >= lenB) {
for (int i = 0; i < lenA; i++) {
if (i < lenB) {
mergedString += a.charAt(i) + "" + b.charAt(i);
} else {
mergedString += a.charAt(i);
}
}
}
if (lenB > lenA) {
for (int i = 0; i < lenB; i++) {
if (i < lenA) {
mergedString += a.charAt(i) + "" + b.charAt(i);
} else {
mergedString += b.charAt(i);
}
}
}
System.out.println("the merged string is-->" + mergedString);
}
}
public static String stringConcate(String str1,String str2){
String str3="";
if(str1!=null && str2!=null && !str1.isEmpty() && !str2.isEmpty()){
if(str1.length()==str2.length()){
for(int i=0;i<=str1.length()-1;i++){
str3+=str1.charAt(i);
str3+=str2.charAt(i);
}
}
if(str1.length()>str2.length()){
for(int i=0;i<=str1.length()-1;i++){
str3+=str1.charAt(i);
if(i<str2.length()){
str3+=str2.charAt(i);
}
}
}
if(str2.length()>str1.length()){
for(int i=0;i<=str2.length()-1;i++){
if(i<str1.length()){
str3+=str1.charAt(i);
}
str3+=str2.charAt(i);
}
}
}
return str3;
}
String str1 = "one"; String str2 = "two";
StringBuilder sb = new StringBuilder();
int i = 0;
for (; i < str1.length() && i < str2.length(); i++) {
sb.append(str1.charAt(i)).append(str2.charAt(i));
}
for(; i < str1.length(); i++) {
sb.append(str1.charAt(i));
}
for(; i < str2.length(); i++) {
sb.append(str2.charAt(i));
}
System.out.println("result = " + sb.toString());// otnweo
This will handle for different length too
This could be donw with very simple if...else.
public static void main(String... args) {
int[] one = { 1, 2, 3 };
int[] two = { 44, 55, 66, 77, 88 };
System.out.println(Arrays.toString(alternate(one, two)));
}
public static int[] alternate(int[] one, int[] two) {
int[] res = new int[one.length + two.length];
for (int i = 0, j = 0, k = 0; i < res.length; i++) {
if (i % 2 == 0)
res[i] = j < one.length ? one[j++] : two[k++];
else
res[i] = k < two.length ? two[k++] : one[j++];
}
return res;
}
Output:
[1, 44, 2, 55, 3, 66, 77, 88]

How can I return multiple variables and/or use a private int method?

Here's my code as it stands:
import static java.lang.System.*;
public class Triples
{
private int number;
public Triples()
{
this(0);
}
public Triples(int num)
{
number = num;
}
public void setNum(int num)
{
number = num;
}
private int greatestCommonFactor(int a, int b, int c)
{
for(int n = 0; n <= number; n++)
{
int max = number;
for(a = 1; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
return 1;
}
}
}
}
}
}
}
return 1;
}
public String toString()
{
String output="";
output = greatestCommonFactor(a, b, c);
return output+"\n";
}
}
I need to have it print out the variables a, b, and c but I can not figure out how to make it do so. The error message I'm currently receiving is "a cannot be resolved to a variable
b cannot be resolved to a variable
c cannot be resolved to a variable"
here's a link to the associated labsheet if it helps: https://docs.google.com/open?id=0B_ifaCiEZgtcX08tbW1jNThZZmM
UPDATE
here's my updated toString method:
public String toString()
{
int a = 0;
int b = 0;
int c = 0;
String output="";
output += greatestCommonFactor(a, b , c) + "\n";
return output;
}
and while I'm editing, my greatestCommonFactor method:
private int greatestCommonFactor(int a, int b, int c)
{
for(int n = 0; n <= number; n++)
{
int max = number;
for(a = 1; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
return greatestCommonFactor(a, b, c);
}
}
}
}
}
}
}
//return 1;
}
UPDATE #2
Here's (hopefully) a more correct way of writing the code for the greatestCommonFactor and toString methods:
private int greatestCommonFactor(int a, int b, int c)
{
a = 0;
b = 0;
c = 0;
for(int n = 0; n <= number; n++)
{
int max = number;
for(a = 1; a <= max; a++)
{
a = n;
for(b = a +1; b <= max; b++)
{
b =n;
for(c = b + 1; c <= max; c++)
{
c = n;
if(Math.pow(a, 2)+ Math.pow(b, 2)== Math.pow(c, 2))
{
if((a%2==1 && b%2==0)|| (a%2==0 && b%2==1))
{
if(a%2<=1 && b%2<=1 && c%2<=1)
{
return a;
}
}
}
}
}
}
}
return greatestCommonFactor(a, b, c);
}
public String toString()
{
String output="";
output += greatestCommonFactor(a, b , c) + "\n";
return output;
}
Runner Class addition
import static java.lang.System.*;
import java.util.Scanner;
public class Lab11j
{
public static void main(String args[])
{
Scanner keyboard = new Scanner(System.in);
String choice="";
do{
out.print("Enter the max number to use : ");
int big = keyboard.nextInt();
//instantiate a TriangleThree object
Triples trip = new Triples( big);
//call the toString method to print the triangle
System.out.println( trip );
System.out.print("Do you want to enter more data? ");
choice=keyboard.next();
}while(choice.equals("Y")||choice.equals("y"));
}
}
You're using variables without declaring and initializing them:
output = greatestCommonFactor(a, b, c); // where are a, b and c decleared in this method?
Moreover, your greatestCommonFactor() method takes arguments, but does nothing else than reinitializing them, so it could very well not take any argument at all:
private int greatestCommonFactor(int a, int b, int c) {
for (int n = 0; n <= number; n++) {
int max = number;
for (a = 1; a <= max; a++)
// here you're setting a to 1. So why pass its value as an argument to the method,
// since you don't care about the passed in value?
EDIT:
instead of having
private int greatestCommonFactor(int a, int b, int c) { // these are arguments
a = 0;
b = 0;
c = 0;
...
}
you should have
private int greatestCommonFactor() {
int a = 0;
int b = 0;
int c = 0; // these are local variables
...
}
Instead of having
public String toString() {
String output="";
output += greatestCommonFactor(a, b , c) + "\n";
return output;
}
you should have
// yes, this method name is ugly, but it says what the method does
// I would simply make greatestCommonFactor a public method, and remove this method,
// since it doesn't do anything useful.
public String computeGreatestCommonFactorAndReturnItAsAStringWithANewLine() {
return greatestCommonFactor() + "\n";
}

Explanation on Java Permutation program

this question might seem basic to some people but I've been analysing and dissecting this code without success as to how this permutation program by Robert Sedgewick prints the combination o f words or characters without using system.out.print in the methods perm1 and perm2. Any help or explanation for dummies is greatly appreciated. Thank you in advance.
This is the code under the link:
public class Permutations {
// print N! permutation of the characters of the string s (in order)
public static void perm1(String s) { perm1("", s); }
private static void perm1(String prefix, String s) {
int N = s.length();
if (N == 0) System.out.println(prefix);
else {
for (int i = 0; i < N; i++)
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
}
}
// print N! permutation of the elements of array a (not in order)
public static void perm2(String s) {
int N = s.length();
char[] a = new char[N];
for (int i = 0; i < N; i++)
a[i] = s.charAt(i);
perm2(a, N);
}
private static void perm2(char[] a, int n) {
if (n == 1) {
System.out.println(a);
return;
}
for (int i = 0; i < n; i++) {
swap(a, i, n-1);
perm2(a, n-1);
swap(a, i, n-1);
}
}
// swap the characters at indices i and j
private static void swap(char[] a, int i, int j) {
char c;
c = a[i]; a[i] = a[j]; a[j] = c;
}
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String elements = alphabet.substring(0, N);
perm1(elements);
System.out.println();
perm2(elements);
}
}
It's right there:
if (N == 0) System.out.println(prefix);
System.out.print and System.out.println is basically the same, except the later prints a newline after the text.

Implementing merge sort in java

Here's my implementation of Merge Sort in java
import java.io.*;
import java.util.Arrays;
public class MergeSort
{
private static int [] LeftSubArray(int [] Array)
{
int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2);
return leftHalf;
}
private static int [] RightSubArray(int [] Array)
{
int [] rightHalf = Arrays.copyOfRange(Array, Array.length / 2 + 1, Array.length);
return rightHalf;
}
private static int [] Sort(int [] A)
{
if(A.length > 1)
{
return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) );
}
else
{
return A;
}
}
private static int [] Merge(int [] B, int [] C)
{
int [] D = new int[B.length + C.length];
int i,j,k;
i = j = k = 0;
while(k < D.length)
{
if(i == B.length)
{
//Copy the remainder of C into D
while(k < D.length){ D[k++] = C[j++]; }
}
if(j == C.length)
{
//Copy the remainder of B into D
while(k < D.length){ D[k++] = B[i++]; }
}
if(i<B.length && j<C.length)
{
if(B[i] > C[j]){ D[k++] = B[i++]; }
else { D[k++] = C[j++]; }
}
}
return D;
}
public static void main(String [] args)
{
int [] array = {1,3,5,2,4};
int [] sorted = MergeSort.Sort(array);
for(int i = 0;i < sorted.length; ++i)
{
System.out.print(sorted[i] + " ");
}
}
}
The output I get is
2 1
From what I can tell there seems a problem with my division of the right sub array.
What am I doing wrong?
Here is the javadoc of copyOfRange:
Parameters:
original - the array from which a range is to be copied
from - the initial index of the range to be copied, **inclusive**
to - the final index of the range to be copied, **exclusive**. (This index may lie outside the array.)
I highlighted two words you should pay special attention to ;-)
If your array has 10 elements, then LeftSubArray copies elements 0..5, and RightSubArray copies elements 6..10. But if the first element is at index 0, then there is no element w/ an index 10. And if copyOfRange(a,b) gives elements indexed a..b-1, then LeftSA is yielding 0..4 and RightSA is yielding 6..9. Either way, your assumption about division seems to be accurate.
With your code [1,3,5,2,4] is split into [1,3] and [2,4]. Good luck
This piece of code works: you had couple of errors:
see next diffs:
rightSubArray method
copy the remainder of B
copy the remainder of C
The code that works follows:
public class MergeSort
{
private static int [] LeftSubArray(int [] Array)
{
int [] leftHalf = Arrays.copyOfRange(Array, 0, Array.length / 2);
return leftHalf;
}
private static int [] RightSubArray(int [] Array)
{
int[] rightHalf = Arrays.copyOfRange(Array, Array.length / 2,
Array.length);
return rightHalf;
}
private static int [] Sort(int [] A)
{
if(A.length > 1)
{
return Merge( Sort( LeftSubArray(A) ) , Sort( RightSubArray(A) ) );
}
else
{
return A;
}
}
private static int [] Merge(int [] B, int [] C)
{
int [] D = new int[B.length + C.length];
int i,j,k;
i = j = k = 0;
while(k < D.length)
{
if(i == B.length)
{
//Copy the remainder of C into D
while (j < C.length) {
D[k++] = C[j++];
}
}
if(j == C.length)
{
//Copy the remainder of B into D
while (i < B.length) {
D[k++] = B[i++];
}
}
if (i < B.length && j < C.length)
{
if (B[i] > C[j]) {
D[k++] = B[i++];
} else {
D[k++] = C[j++];
}
}
}
return D;
}
public static void main(String [] args)
{
int [] array = {1,3,5,2,4};
int [] sorted = MergeSort.Sort(array);
for(int i = 0;i < sorted.length; ++i)
{
System.out.print(sorted[i] + " ");
}
}
}
I found a rigth solution in Robert Sedgewick book "Algorithms on java language"
Read here about merge

Categories