It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
How would I sort a char array in Java? I know I can use java.util.Arrays.sort(), but if I manually want to sort it? Using bubble sort or something?
Notice the string is "cab", the sorted result should be "abc". I don't know how to sort this, i know how to sort integers, but i don't know how to sort char arrays.
Here's my code:
String s1 = "cab";
char[] arr;
arr = s1.toCharArray();
//Could use
//java.util.Arrays.sort(arr);
//But want to do it manually using something like bubble sort
s1 = new String(arr);
characters can be directly compared as the comparison operators are overloaded. w>q i.e
arr[1]>arr[0]
is valid and gives true. So just treat them like integers in the bubble sort algorithm.
Using bubble sort or something?
Yes, a bubble sort would work. Or you could use any one of the other well-known sort algorithms; e.g. as listed in this Wikipedia page ... or any good textbook on data structures and algorithms.
(But no, I'm not going to code this for you.)
I have no idea weather this solution is the best way, and to be honest I don't think it is.
But I'v made a little piece of code which sorts an array in the following steps:
Make a for loop that goes from 0 to array.size() * array.size().
Make a index variable (int) which is 0 out side the loop
in the loop add a try catch and catch OutOfBoundsException, in the catch set index to 0.
In the try you get 'index' of your array,
char c = array[index]
And compare to index +1
c.compareTo(array[index +1])
If that's a positive number >0 you switch the two items' positions array[index] and array[index + 1]
If it doesn't make sense to you I can provide a code sample, but not before 2 hours from now, approximately..
This is what I meant:
public static ArrayList<mContact> SortByName(ArrayList<mContact> arr)
{
int i = 0;
for (int o = 0; o < arr.size() * arr.size(); o++)
{
try
{
int c = arr.get(i).getName().compareTo(arr.get(i + 1).getName());
if (c > 0)
{
mContact con = new mContact(arr.get(i).getName());
arr.get(i).setName(arr.get(i+1).getName());
arr.get(i+1).setName(con.getName());
}
i++;
}
catch (IndexOutOfBoundsException ex)
{
i = 0;
}
}
return arr;
}
That sorts the List by the contacts Name in ascending order.
The compareTo Method returns a integer that represents the diffrence of the two strings. and 0 if they are the same!
You can compare ASCII values of each of the characters or convert each of the to int using parseInt and compare their values.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm currently learning Java and I stumbled on an exercise I can't finish.
The task is to write a recursive method that takes an array and returns the difference of the greatest and smallest value.
For example {12, 5, 3, 8} should return 5 (8 - 3). It is important to note that it is only allowed to compare values in their right order (result = rightValue - leftValue). For example 12-3 = 9 would not be allowed. Think of it like stock values. You want to find out which time to buy and sell the stocks to make the largest profit.
It was quiet easy to implement this iterative but I have no idea how to do it recursive. Also it is part of the task to solve it by using divide and conquer.
I've used divide and conquer approach here. I believe the trick here is to include middle in both the arrays that we're splitting the main array into.
/* edge cases ignored here */
int findMax(int[] arr, int left, int right){
if(right-left == 1) return (arr[right]-arr[left]);
int middle = left + (right-left)/2;
int max1 = findMax(arr, left, middle);
int max2 = findMax(arr, middle, right);
if(max1 >= 0 && max2 >= 0) return max1+max2;
else return Math.max(max1,max2);
}
Well I don't think recursion is very effective on this. You would probably never do this(other than homework). Something like this would do it:
int findGreatestDifference(Vector<Integer> numbers, int greaterDifference){
if(numbers.size() == 1 ) //return at last element
return greaterDifference;
int newDifference = (numbers.get(0) - numbers.get(1));
if (newDifference > greaterDifference)
greaterDifference = newDifference;
numbers.remove(numbers.size() - 1);
findGreatestDifference(numbers, greaterDifference);
return greaterDifference;
}
first time you call it, pass 0 as the greater difference, and again I don't find this as an effective way to do it. Iteration would be way better for this.
I hope this helps.
Algorithm (this is pretty much a sort task , then the subtraction step is trivial)
1) First sort the arrays (use recursive merge sort for large arrays and recursive insertion for smaller arrays).
Merge sort (https://en.wikipedia.org/wiki/Merge_sort)
Insertion sort (https://en.wikipedia.org/wiki/Insertion_sort)
2) Use the arrays smallest index[0] to get the smallest value & index[array.length-1] to get the largest
3)compute the difference (dont know what you mean by right order?)
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I wrote the following code to sort the elements in the array values using a BubbleSort. Is this correct or is there anything missing? My test cases are good, but maybe it's the test cases that are also missing something.
public void sort(ValuePair[] values) {
ValuePair value = null;
for (int i = 0; i < values.length; i++) {
for (int j = 1 + i; j < values.length; j++) {
if (values[i].getValue() > values[j].getValue()) {
value = values[j];
values[j] = values[i];
values[i] = value;
}
}
}
}
Your code is correct in that it will sort the array. However it will always require N*(N-1) passes over the array. This is not
the typical algorithm used to implement
a bubble sort. The typical algorithm uses repeat loop with a test for sorted. This is somewhat more efficient because it
terminates as soon as the array is sorted (consider the case where you start with a sorted array).
Read the Wikepedia article on bubble sort it demonstrates this very well.
A somewhat improved version pseudocode version of Bubble Sort goes something like this:
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
if A[i-1] > A[i] then
swap(A[i-1], A[i])
swapped = true
end if
end for
n = n - 1
until not swapped
end procedure
The lesson here is that while your algorithm and the Wikepedia algorithm both have the same big O characteristics, a small change
in the way they have been implemented can make a significant difference in their actual performance characteristics.
I am exceptionally new to programming, but I am working on improving my skills as a programmer. Currently, I am working on a problem I gave myself where I am trying to take a variable number and make each of its digits a separate number in an array. I don't care about the order of the digits, so if they are reversed, then it doesn't matter to me. I know people have asked this question numerous times, but they always seem to use a lot of things that I don't understand. Since my school doesn't offer any Java courses, I only know what I have learned on my own, so if you could explain any terms you use in the code that aren't extremely trivial, that would be wonderful. Right now, I have written:
int number = 1234567890;
while (number > 0) {
System.out.println(number%10);
number = number/10;
This works fine for printing the digits individually, but I can't figure out how to add them to the array. I greatly appreciate any help you can give, and please keep in mind that I much prefer simplicity over small size. Thank you in advance!
P.S. Some responses I've seen for similar questions include what I think are arrays of strings. In order for the part of the program that I have working to still work, I think that I need to use an array of integers. If you're curious, the rest of the code is used to determine if the numbers in the array are all different, in order to achieve the final result of determining if a number's digits are all distinct. It looks like this:
int repeats=0;
int[] digitArray;
digitArray = new int[10];
for (int i = 0; i < digitArray.length; i++)
for (int j = 0; j < digitArray.length; j++)
if ((i != j) && (digitArray[i]==digitArray[j])) unique = unique+1;
System.out.println(unique==0);
Method number.toString().length() will return the number of digits. That is the same as the length of your needed array. Then you use your code as before, yet instead of printing you add the digit to the array.
int number = 1234567890;
int len = Integer.toString(number).length();
int[] iarray = new int[len];
for (int index = 0; index < len; index++) {
iarray[index] = number % 10;
number /= 10;
}
I would rather suggest you to use an ArrayList, since to use an array, you would have to allocate the size in advance, for which you need to know the number of digits in your number, which you don't know.
So, either work with an array, and do the iteration over the number twice - once for finding size, and next for doing actual work. Else, move ahead with an ArrayList.
Adding an element to an ArrayList is quite simple. You just need to call - List#add(E) method with appropriate parameter.
So, here's an extension of your solution: -
// Declare a List<Integer>, since it will store integers only.
List<Integer> digits = new ArrayList<Integer>():
int number = 1234567890;
while (number > 0) {
int digit = number % 10; // Store digit in a variable
number = number/10;
// Add digit to the list
digits.add(digit);
}
Alternatively, if you want to have only unique digits in your List, then you should use a HashSet, which automatically removes the duplicates.
With Java 8:
Integer.toString(n).chars().map(a->a-'0').toArray()
char [] arr = scan.next().toCharArray();
This code will read a number from scan.next() and then it is going to give it as an input to char array which will have the number at its indices as single digit by digit.
Hope this will help.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
What is the easiest way to find the largest and smallest element in an array and print its index location without using an algorithm. Is there a way to do it using a loop or if statement as i am new to java and it is as far as my knowledge goes for now.
This is my code for the array:
import java.io.*;
public class Tut2ArraysQ4
{
public static void main(String [] args) throws IOException
{
BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
int []item=new int[5];
for (int i = 0; i < item.length; i++)
{
System.out.println("Enter a number: ");
int num=Integer.parseInt(kbd.readLine());
System.out.println("Index " + i + " Contains Number " + num);
}
}//end class
}//end main
i am grateful for your help
You declare two variables equal to the element in the first position of your array, and two equal to the first position.
int min = array[0];
int max = array[0];
int posMin = 0;
int posMax = 0;
Make a for to iteration over all position of the array:
for(all the position of the array)
// if current position bigger than max
// max = element of the array in the current position
// posMin = current position
// if current position smaller than min
// min = element of the array in the current position
// posMax = current position
Another approach is sorting the array, the smallest element will be in the first position and the biggest on the last position of the array. However, this solution takes typically N lg N while the first one I post performance in N. If you are using radix sort it will take k N, but:
Sometimes k is presented as a constant, which would make radix sort
better (for sufficiently large n) than the best comparison-based
sorting algorithms, which are all O(n·log(n)). However, in general k
cannot be considered a constant.
read more about
I'm sorry, but unfortunately, There is no way to do what you're trying to do without using an Algorithm.
Even if you pick 2 numbers and prey that you're right, you'll be using an algorithm.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'd like to create a matrix like this one:
It's the transform of a graph in a matrix where a, b, c and so on are the vertices and the values represent 0 if the vertices are disconnected and 1 if they're connected.
I take two vertices randomply (i.e. c and d) and I'd like to access the value of those vertices in the matrix as M[c][d] and, also, M[d][c].
How can I do this?
If you will use integer indexes instead of letters you will be able to say m[2][3], if the matrix is defined as: int[][] m;
If you need to access the values using string coordinates, probably you should take a look at the Table class from Guava, see: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html.
This way, you will be able to declare your matrix like: Table<String,String,String> and insert values using: put(String rowKey, String columnKey, String value) method and access them using get(String rowKey, String columnKey)
If you trylly want to use letters (chars) as indexes then you'll have to take an alternative approach. You can create your own structure that takes char as an index. Since a two dimensional array can be seen as an array of arrays, you can use a Map or Map objects.
You won't be able to access the objects the way you expect with this, instead you'll have to invoke map.get('c').get('d').
Another approach is to create a sort of "rosetta stone" that translates your char into the corresponding index. This is particulary useful for small graphs, since big ones generate inmense matrices and getting the index there depends on how will you address them. For example:
public class IndexInterpreter {
//Using a switch here to illustrate, you can make your own mapping logic.
public static int getIndex(char letter) {
switch(letter) {
case 'a':
return 0;
case 'b':
return 1;
//the swtich goes on and on...
}
}
}
and then, while calling the matrix you just translate the letters into their corresponding indexes:
int i1 = IndexInterpreter.getIndex('c');
int i2 = IndexInterpreter.getIndex('d');
m[i1][i2]
or, if you like
m[IndexInterpreter.getIndex('c')][IndexInterpreter.getIndex('d')]
matrix would be a 2D array
String[][] matrix = new String[6][7]
you could then populate it using
matrix[1][1] = "1";
To get the cell you want you wuld do
String val = mattix[3][5];
This link may help