This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
main class
public CustomString[] split(char delimiter) {
// char n;
char[] split = null;
int numOfSplit = 1;
int objectLocation=0;
for (int h = 0; h < this.data.length; h++) {
if (delimiter == this.data[h]) {
numOfSplit++;
}
}
CustomString[] splitter = new CustomString[numOfSplit];
for (int i = 0; i < this.data.length; i++) {
if (delimiter == this.data[i]) {
// n = 32;//unicode for space}
split = new char[i];
for (int j = 0; j < split.length; j++) {
char z = this.data[j];
split[j] = z;
objectLocation++;
}
}
splitter[objectLocation] = new CustomString(split);
}
return splitter;
}
tester class:
System.out.print("Delimiter: ");
String delimiter = input.next();
char[] deli = delimiter.toCharArray();
char delim = deli[0];
System.out.println("Splitted String: " + blah.split(delim));
result: [LCustomString;#55f96302
main class completed
import java.util.Scanner;
import java.util.Arrays;
public class CustomString {
private char[] data;
public CustomString() {
} // no arg constructor
public CustomString(char[] data) {
this.data = data;
} // constructor
public CustomString changeCase() { // type: CustomString
char n;
char[] newArray = new char[this.data.length];// this.data;
// char charNewA
for (int i = 0; i < newArray.length; i++) {
n = this.data[i];
// char[] number = new char[1];
if (n >= 65 && n <= 90) {
n += 32;
}// if capital char change to lower char
else if (n >= 97 && n <= 122) {
n -= 32;
}// if lower char change to capital char
// create a new array with n properties
newArray[i] = n;
}
return new CustomString(newArray);
} // returns a new CustomString where the case of each letter is changed to
// the opposite
public char charAt(int index) {
char charIndex = this.data[index - 1];
return charIndex;
} // returns character as a given index
public int compareTo(CustomString rhs) { // take off comments
int value = 0;
int loopSize;
if (this.data.length < rhs.data.length) {
loopSize = this.data.length;
} else {
loopSize = rhs.data.length;
}
for (int i = 0; i < loopSize; i++) {
char char1 = this.data[i];
char char2 = rhs.data[i]; // should be equal to 2nd customString
if (char1 != char2) {
value = char1 - char2;
// if (char1 > char2) {
// value = char1-char2; //pos??
// } else if (char1 < char2) {
// value =
// }
}
}
return value;
} // compares 2 strings lexographically. return 0 if two same. return + is
public int compareToIgnoreCase(CustomString rhs) {
char[] newArrayCompareToIgnoreCase = new char[this.data.length];
// newArrayCompareToIgnoreCase = this.data;
char[] newArrayCompareToIgnoreCase2 = new char[rhs.data.length];
// newArrayCompareToIgnoreCase2 = rhs.data;
char n, m;
int value = 0;
int loopSize;
if (this.data.length < rhs.data.length) {
loopSize = this.data.length;
} else {
loopSize = rhs.data.length;
}
for (int i = 0; i < loopSize; i++) {
n = this.data[i];
// char[] number = new char[1];
if (n >= 97 && n <= 122) {
n -= 32;
}// if lower char change to capital char
newArrayCompareToIgnoreCase[i] = n;
m = rhs.data[i];
if (m >= 97 && m <= 122) {
m -= 32;
}// if lower char change to capital char
newArrayCompareToIgnoreCase2[i] = m;
// by now everything should be lowercase
for (int j = 0; j < loopSize; j++) {
char char1 = newArrayCompareToIgnoreCase[j];
char char2 = newArrayCompareToIgnoreCase2[j];
if (char1 == char2) {
value = 0;
}
if (char1 != char2) {
value = char1 - char2;
}
}
}
return value;
} // compares two string but casing douse not matter
public CustomString concat(CustomString rhs) {
char n, m;
char[] newArrayConcat = new char[this.data.length + rhs.data.length + 2];
for (int i = 0; i < this.data.length; i++) {
n = this.data[i];
// m = rhs.data[i];
newArrayConcat[i] = n;
// newArrayConcat[i+this.data.length]= m;
}
for (int j = 0; j < rhs.data.length; j++) {
m = rhs.data[j];
newArrayConcat[j + this.data.length] = m; // +1
}
return new CustomString(newArrayConcat); // change?
}// returns a new CustomString object by concatenating source string and
// parameter string
// CustomString
public boolean equals(CustomString rhs) {
char[] newArrayEquals = new char[this.data.length];
char[] newArrayEquals2 = new char[rhs.data.length];
boolean equals = false;
int length;
char n, m;
if (this.data.length > rhs.data.length) {
length = rhs.data.length;
} else {
length = this.data.length;
}
for (int i = 0; i < length; i++) {
n = this.data[i];
m = rhs.data[i];
newArrayEquals[i] = n;
newArrayEquals2[i] = m;
}
for (int j = 0; j < length; j++) {
char char1 = newArrayEquals[j];
char char2 = newArrayEquals2[j];
if (char1 != char2) {
equals = false;
break;
} else if (char1 == char2) {
equals = true;
}
}
return equals;
} // Returns true or false based on whether or not the two strings are
// equal. NOTE: Does not ignore case
public boolean equalsIgnoreCase(CustomString rhs) {
int length;
if (this.data.length > rhs.data.length) {
length = rhs.data.length;
} else {
length = this.data.length;
}
char[] newArrayEqualsToIgnoreCase = new char[this.data.length];
char[] newArrayEqualsToIgnoreCase2 = new char[rhs.data.length];
char n, m;
boolean equalsIgnoreCase = false;
for (int i = 0; i < length; i++) { // must compare which string is
// longer or else if
// //newArrayEqualsToIgnoreCase.length
n = this.data[i];
m = rhs.data[i];
if (n >= 65 && n <= 90) {
n += 32;
}
if (m >= 65 && m <= 90) {
m += 32;
}// changes everything to lower case
newArrayEqualsToIgnoreCase[i] = n;
newArrayEqualsToIgnoreCase2[i] = m;
}
for (int j = 0; j < length; j++) { // this.data.length
char char1 = newArrayEqualsToIgnoreCase[j];
char char2 = newArrayEqualsToIgnoreCase2[j];
if (char1 != char2) {
equalsIgnoreCase = false;
break;
} else if (char1 == char2) {
equalsIgnoreCase = true;
}
}
return equalsIgnoreCase; // change?
} // Same as equals but ignores the case
public int length() {
int charLength = this.data.length;
return charLength; // change?
} // Returns the length of the CustomString object
public CustomString[] split(char delimiter) {
// char n;
char[] split = null;
int numOfSplit = 1;
int objectLocation=0;
for (int h = 0; h < this.data.length; h++) {
if (delimiter == this.data[h]) {
numOfSplit++;
}
}
CustomString[] splitter = new CustomString[numOfSplit];
for (int i = 0; i < this.data.length; i++) {
if (delimiter == this.data[i]) {
// n = 32;//unicode for space}
split = new char[i];
for (int j = 0; j < split.length; j++) {
char z = this.data[j];
split[j] = z;
objectLocation++;
}
}
splitter[objectLocation] = new CustomString(split);
}
return splitter;
} // Returns a CustomString array, where each element of the array is a
// CustomString object created by splitting the source string based
// on the given char delimiter. This is an easier version of the split
// method provided in the String class and
// you only need to split on one character. The output array should NOT
// contain the delimiter character.
public boolean startsWith(CustomString prefix) {
boolean startsWithEqual = false;
char[] startsWith1 = new char[prefix.data.length];
char[] startsWith2 = new char[prefix.data.length];
char m, n;
for (int i = 0; i < prefix.data.length; i++) {
m = this.data[i];
n = prefix.data[i];
startsWith1[i] = m;
startsWith2[i] = n;
}
for (int j = 0; j < prefix.data.length; j++) {
if (startsWith1[j] == startsWith2[j]) {
startsWithEqual = true;
}
if (startsWith1[j] != startsWith2[j]) {
startsWithEqual = false;
break;
}
}
return startsWithEqual;
} // Returns true if the source CustomString starts with the given prefix
public boolean endsWith(CustomString suffix) {
boolean endsWithEqual = false;
char[] endsWith1 = new char[suffix.data.length];
char[] endsWith2 = new char[suffix.data.length];
char m, n;
for (int i = 0; i < suffix.data.length; i++) {
n = suffix.data[i];
endsWith2[i] = n;
}
int k = 0;
for (int i = this.data.length - suffix.data.length; i < this.data.length; i++) {
m = this.data[i];
endsWith1[k] = m;
k++;
}
for (int j = 0; j < suffix.data.length; j++) {
if (endsWith1[j] == endsWith2[j]) {
endsWithEqual = true;
}
if (endsWith1[j] != endsWith2[j]) {
endsWithEqual = false;
break;
}
}
return endsWithEqual;
}
// Returns true if the source CustomString contains the parameter
public CustomString substring(int srcBegin) {
char[] newArraySub1;
if (srcBegin == 0) {
newArraySub1 = new char[this.data.length - srcBegin];
} else {
newArraySub1 = new char[this.data.length - srcBegin + 1];
}
char n;
for (int i = srcBegin; i < newArraySub1.length; i++) {
n = this.data[i];// -1
newArraySub1[i] = n;
}
return new CustomString(newArraySub1);
} // Returns a new CustomString object created by finding the substring of
// the source string starting
// with src Begin and going to the end of the source string
public CustomString substring(int srcBegin, int srcEnd) {
char n;
char[] newArraySub2 = new char[this.data.length - srcBegin];
for (int i = srcBegin; i < srcEnd; i++) {
n = this.data[i];
newArraySub2[i] = n;
}
return new CustomString(newArraySub2);
}// Returns a new CustomString object created by finding the substring of
// the source starting with srcBegin and ending at srcEnd –
public CustomString titleize() {
char n, m;
char[] titleizedChar = new char[this.data.length];
for (int j = 0; j < this.data.length; j++) {
m = this.data[j];
if (m >= 65 && m <= 90) {
m += 32;
titleizedChar[j] = m;
}
for (int i = 0; i < 1; i++) {
n = this.data[i];
if (n >= 97 && n <= 122) {
n -= 32;
}
titleizedChar[i] = n;
}
titleizedChar[j] = m;
}
return new CustomString(titleizedChar); // change?
} // Returns a new CustomString object where the first character or every
// word is capitalized.
public CustomString toLowerCase() {
char[] toLowCase = new char[this.data.length];
for (int i = 0; i < toLowCase.length; i++) {
char n = this.data[i];
if (n >= 65 && n <= 90) {
n += 32;
}
toLowCase[i] = n;
}
return new CustomString(toLowCase);
} // Returns a new CustomString object with all lower case letters.
public CustomString toUpperCase() { // should be similar to lower case do
char[] toUpperCase = new char[this.data.length];
for (int i = 0; i < toUpperCase.length; i++) {
char n = this.data[i];
if (n >= 97 && n <= 122) {
n -= 32;
}
toUpperCase[i] = n;
}
return new CustomString(toUpperCase);
} // Returns a new CustomString object with all upper case letters.
public String toString() {
String toString1 = "";
for (int i = 0; i < this.data.length; i++) {
char n = this.data[i];
toString1 += n;
}
return toString1;
} // Returns a String representation of the CustomString object. This is the
// only place where you are allowed to use a String variable to build
// the output string and return it.
}// end of code
I'm trying to print each object inside the array but dont know how? Note: i already have a toString method.
Edit: I changed the main class from the original post at 10:45 pm i posted the wrong one
You could use
java.util.Arrays.toString(blah.split(delim));
For this to work, your CustomString class would need to provide a toString() method, too.
As per your question the blah.split(delim) is supposed to return an array of CustomString data type .
I am asuming that you have a class called CustomString ..
so in order to convert From CustomString type to normal string type you need to be specific about the CustomString .
Please mention the contents of the Class CustomString so that we could help you out
ok by the look of CustomString class it is storing an array of datatype char so but the problem is that the return type of split(delim) is an array of datatype CustomString so you will face problems while unboxing with tostring() .. give me a minute
You can use
System.out.println(new String(charArray))
or
Arrays.toString(charArray)
to convert character array into string for printing purpose.
you can also refers to
What does the output of a printed character array mean?
Instead of reading char 1 by 1 and append in the string. Simple use new String(data)
Unboxing Might help
try
System.out.println("Splitted String: " + blah.split(delim).toString());
Related
I'm supposed to write an algorithm that tests two Strings to check if they're anagrams of each other and I have to use either BubbleSort, SelectionSort or InsertionSort.
So I used SelectionSort to sort the Strings, which I converted to char arrays beforehand, but it doesn't work and I cannot find my mistake.
public static void selectionSort(char[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int least = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[least])
least = j;
if (least != i) {
int swap = arr[i];
arr[i] = arr[least];
arr[least] = (char) swap;
}
}
}
}
public static boolean anagramCheck(String x, String y) {
x.trim();
y.trim();
x.toLowerCase();
y.toLowerCase();
char xarr[] = x.toCharArray();
char yarr[] = y.toCharArray();
if (x.length() != y.length())
return false;
selectionSort(xarr);
System.out.println(xarr); // I used this to check if the Strings are sorted correctly
selectionSort(yarr);
System.out.println(yarr);
if (xarr == yarr) {
System.out.println("It's an anagram.");
return true;
} else {
return false;
}
}
I'm supposed to ignore capital letters and spaces, that's why I used trim() and toLowerCase(). But it neither trims the spaces nor changes capital letters to lower case letters. Additionally, when I use more than 5 letters, it doesn't sort the given Strings alphabetically. Only one of both is sorted correctly, the other one is messed up.
I am new to Java programming so I might need some help here.
Thanks in advance
Check where I did the modification:
public static void selectionSort(char[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int least = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[least])
least = j;
}
if (least != i) {
int swap = arr[i];
arr[i] = arr[least];
arr[least] = (char) swap;
}
}
}
In anagramCheck function:
x = x.trim(); // it returns trim string
y = y.trim();
x = x.toLowerCase(); // return lower-case string
y = y.toLowerCase();
This should work. But I used bubbleSort
class HelloWorld {
public static void main(String[] args) {
System.out.println(anagramCheck("listen", "silent"));
}
public static boolean anagramCheck(String x, String y) {
x = x.trim();
y = y.trim();
x = x.toLowerCase();
y = y.toLowerCase();
char xarr[] = x.toCharArray();
char yarr[] = y.toCharArray();
if (x.length() != y.length())
return false;
x = bubbleSort(xarr);
System.out.println(xarr); // I used this to check if the Strings are sorted correctly
y = bubbleSort(yarr);
System.out.println(yarr);
if (x.equals(y)) {
System.out.println("It's an anagram.");
return true;
} else {
return false;
}
}
public static String bubbleSort(char[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++){
for (int j = 0; j < n-i-1; j++){
if (arr[j] > arr[j+1])
{
// swap arr[j+1] and arr[j]
char temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return String.valueOf(arr);
}
}
I'm trying to build a function, that gets a string of letters, and prints the amount of each letter in the string.
for example:
input: String = "aaabbaccxyxyx"
output: 4a2b2c3x2y
This is what I've come up with:
public class Q1 {
public static String numLetters(String s){
String end = new String();
int counter = 0;
char c,d;
for(int i=0; i<s.length();i++){
c = s.charAt(i);
for(int j=0; j<s.length();j++){
d = s.charAt(j);
if(c == d){
counter++;
}
}
end = end + counter+c;
counter = 0;
}
return end;
}
but, this is the output: 4a4a4a2b2b4a2c2c3x2y3x2y3x
A lot of repeats..
Any help how to make it right?
Keep in mind, the function needs to return a string, not just prints it out.
Thanks! =)
I would make an int array to keep the count of each letter in in the string. Because there are 26 letters, the length of the array should be 26:
public static String numLetters(String s) {
int[] count = new int[26];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
count[(int)(c - 'a')]++;
}
String ans = "";
for (int i = 0; i < 26; i++) {
if (count[i] != 0) {
ans += String.valueOf(count[i]) + (char)(i + 'a');
}
}
return ans;
}
A straightforward variant could look like this:
public static String countChars(String arg) {
String res = "";
boolean[] counted = new boolean[arg.length()];
for (int i = 0; i < counted.length; i++) {
if (!counted[i]) {
char c = arg.charAt(i);
int counter = 1;
for (int j = i + 1; j < counted.length; j++) {
if (arg.charAt(j) == c) {
counter++;
counted[j] = true;
}
}
res += counter + "" + c;
}
}
return res;
}
If you want to keep your original structure, I suggest using a StringBuilder so that you can delete characters that you have already seen. In case you delete a character, you have to adjust your indexes i and j.
public static String numLetters(String str){
StringBuilder s = new StringBuilder(s);
String end = new String();
int counter = 0;
char c,d;
for(int i=0; i<s.length();i++){
c = s.charAt(i);
for(int j=0; j<s.length();j++){
d = s.charAt(j);
if(c == d){
s.deleteCharAt(j);
if (i >= j) i--;
j--;
counter++;
}
}
end = end + counter+c;
counter = 0;
}
return end;
}
Try this:
int count = StringUtils.countMatches("a.b.c.d", ".");
This question already has answers here:
Counting the number of a certain letter appears in series of strings in an ArrayList
(4 answers)
Closed 6 years ago.
I have an ArrayList that stores strings, or notes, in the form of "walk the dog". I have a notes class with a method that prints the number of times each letter appears in the entire ArrayList. I'm supposed to declare and use a primitive array of ints of size 26 and turn each letter in the notebook into a char using the charAt method in the String class. Then I have to use that char to index into the appropriate location in the low-level array. This is my method so far but it's not finished:
public void printLetterDistribution() {
ArrayList<Integer> aList = new ArrayList<Integer>();
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
int code = (int)letter;
aList.add(code);
}
}
Collections.sort(aList);
}
I've hit a wall and I don't know how to continue. As you can see, I've tried to convert the letters to their character code but it's probably not the best way to do it and I'm still getting stuck. Can anybody help?
EDIT - Here is the entire notes class:
public class Notebook {
private ArrayList<String> notes;
public Notebook() { notes = new ArrayList<String>(); }
public void addNoteToEnd(String inputnote) {
notes.add(inputnote);
}
public void addNoteToFront(String inputnote) {
notes.add(0, inputnote);
}
public void printAllNotes() {
for (int i = 0; i < notes.size(); i++) {
System.out.print("#" + (i + 1) + " ");
System.out.println(notes.get(i));
}
System.out.println();
}
public void replaceNote(int inputindex, String inputstring) {
int index = inputindex - 1;
if (index > notes.size() || index < 0) {
System.out.println("ERROR: Note number not found!");
} else {
notes.set(index, inputstring);
}
}
public int countNotesLongerThan(int length) {
int count = 0;
for (int i = 0; i < notes.size(); i++) {
String temp = notes.get(i);
if (temp.length() > length) {
count++;
}
}
return count;
}
public double averageNoteLength() {
int sum = 0;
for (int i = 0; i < notes.size(); i++) {
String temp = notes.get(i);
int length = temp.length();
sum += length;
}
double average = (double)(sum / notes.size());
return average;
}
public String firstAlphabetically() {
String min = "";
for (int i = 0; i < notes.size(); i++) {
for (int j = i + 1; j < notes.size(); j++) {
if ((notes.get(i)).compareTo(notes.get(j)) < 0) {
min = notes.get(i);
} else {
min = notes.get(j);
}
}
}
return min;
}
public void removeNotesBetween(int startnote, int endnote) {
int start = startnote - 1;
int end = endnote - 1;
for (int i = end - 1; i > start; i--) {
notes.remove(i);
}
}
public void printNotesContaining(String findString) {
for (int i = 0; i < notes.size(); i++) {
if (notes.get(i).contains(findString)) {
System.out.println("#" + i + " " + notes.get(i));
}
}
}
public int countNumberOf(String letter) {
int count = 0;
for (int i = 0; i < notes.size(); i++) {
String note = (notes.get(i));
for (int j = 0; j < note.length(); j++) {
if (note.charAt(j) == letter.charAt(0)) {
count++;
}
}
}
return count;
}
public void findAndReplaceFirst(String old, String newWord) {
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
if (note.contains(old)) {
int loc = note.indexOf(old);
int len = old.length();
String temp = note.substring(0, loc ) + note.substring(loc + len, note.length());
String newString = temp.substring(0, loc) + newWord + temp.substring(loc, temp.length());
notes.set(i, newString);
} else {
String newString = note;
notes.set(i, newString);
}
}
}
public void printLetterDistribution() {
int[] p = new int[26];
for (int i = 0; i < 26; i++) {
p[i] = 0;
}
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
note = note.toLowerCase();
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
p[letter - 'a']++;
}
}
System.out.println(p);
}
}
You can use an int array of 26 length and increment the count of the index letter-'a';
int[] p = new int[26];
for(int i = 0; i < 26; i++) p[i] = 0;
for (int i = 0; i < notes.size(); i++) {
String note = notes.get(i);
for (int j = 0; j < note.length(); j++) {
char letter = note.charAt(j);
if(letter>= 'a' && letter <= 'z')
p[letter-'a']++;
}
PS: I am assuming that the notes are in lowercase only. If it is not the case, use note.toLowerCase() to make them lower.
Since in your notes you can have spaces, I have updated the code.
What I need to do is take a String array with each element having an exact length of 2, and find all possible combinations of the the elements, using each character within each String. By that I mean the String array {"Ss", "Ff"} returns "SF", "Sf", "sF", "sf". I have already tried a loop method that counts the iteration and then chooses a letter based on that, but it only works for arrays with a single element:
public String [] generatePossibilities(String [] s)
{
if(s[0].length() != 2)
throw new IllegalArgumentException();
String [] r = new String [s.length * 2];
for(int i = 0; i < r.length; i++)
{
r[i] = getPossibility(i, s);
}
return r;
}
private String getPossibility(int iteration, String [] source)
{
int [] choose = new int [source.length];
for(int i = 0; i < choose.length; i++)
{
choose[i] = 0;
}
for(int i = choose.length - 1; i >= 0; i--)
{
if(iteration < 1)
break;
choose[i] = 1;
iteration--;
}
String result = "";
for(int i = 0; i < source.length; i++)
result += source[i].substring(choose[i], choose[i] + 1);
return result;
}
Solved Thanks Sven!
public String [] generatePossibilities(String [] s)
{
if(s[0].length() != 2)
throw new IllegalArgumentException();
ArrayList<String> ra = new ArrayList<String>();
for(int i = s.length - 1; i >= 0; i--)
{
for(int j = 0; j < s[i].length(); j++)
{
String c = s[i].substring(j, j + 1);
if(ra.size() < 2)
{
ra.add(c);
}
else
{
for(int k = 0; k < ra.size(); k++)
{
String s1 = ra.get(k);
if(s1.substring(0, 1).equalsIgnoreCase(c))
continue;
else
{
s1 = c + s1;
ra.add(s1);
}
}
}
}
for(int j = 0; j < ra.size(); j++)
{
if(ra.get(j).length() != s.length - i)
{
ra.remove(j);
j--;
}
}
}
String [] r = new String [ra.size()];
for(int i = 0; i < r.length; i++)
{
r[i] = ra.get(i);
}
return r;
}
I would iterate the array of character tuples from last element to first. In each step you append to each current character the possibilities of the last iteration. You therefore double the elements in each step.
So for your example in the first iteration you have {Ff} and this would result to the two strings "F" and "f". In the next step you take each character of {Ss} and append each string of the last step to it getting "SF", "Sf", "sF" and "sf". You could then continue with further character tuples.
I am trying to extend the following code to sort the array if I added a third value 'C'. Would this be possible to do while retaining only one loop. The following code will sort an array with two possible values 'A' and 'B'.
public class TestSort
{
public static void main(String args[])
{
char f[] = {'A','B','B','A','B','B','A','B','A','A','B'};
int k = 0, t = f.length-1;
while(k < t)
{
if(f[k] == 'A')
k = k + 1;
else if(f[k] == 'B')
{
char m = f[t];
f[t] = f[k];
f[k] = m;
t = t - 1;
}
}
System.out.print("\nSorted List\n");
for(char i : f)
System.out.print(i + ", ");
System.out.println();
}
}
Here is an attempt. I don't know if I'm on the right track.
public class TestSort
{
static char f[] = {'C','A','B','A','C','B','A','B','C','C','B','A','B'};
//static char f[] = {'A','A','A','A','A','C','A','C','A','A','C','A','C'};
//static char f[] = {'C','B','B','B','C','B','B','B','C','C','B','C','B'};
//static char f[] = {'A','B','B','B','A','B','C','B','A','A','B','A','B'};
public static void main(String args[])
{
int j = 0, k = 0, t = f.length-1, l = f.length-1;
while(t >= 0)
{
if(f[k] == 'A')
k = k + 1;
else if(f[k] == 'B')
{
char m = f[j];
f[j] = f[k];
f[k] = m;
j = j + 1;
}
else if(f[k] == 'C')
{
char m = f[l];
f[l] = f[k];
f[k] = m;
l = l - 1;
}
for(char i : f)
System.out.print(i + ", ");
System.out.println();
}
}
}
Maybe something like:
public sort(char[] array) {
int[] frequencies = new int[3];
for(char c : array) {
if (c == 'A')
frequencies[0]++;
if (c == 'B')
frequencies[1]++;
if (c == 'C')
frequencies[2]++;
}
int index = 0;
for (int i = 0; i < frequencies[0]; i++) {
array[index++] = 'A';
}
for (int i = 0; i < frequencies[1]; i++) {
array[index++] = 'B';
}
for (int i = 0; i < frequencies[2]; i++) {
array[index++] = 'C';
}
}
Is the requirement "keep it O(n)", or "keep one loop" ?
Adding a second (non-nested) loop wouldn't change the O(n) quality. then you could do it in two steps: first push all the 'A's to the start and a second one to push all the 'C's to the end.