I am looking to print out my original unsorted array, I have it printing in order and sorted but I can't seem to get the original one to print out unsorted. I have used printRuleAndArray(String rule) and I have also used LengthCompare for the new sorted array, my problem is the original!!!
import java.util.*;
import java.util.Arrays;
// Example of how to sort an array
public class Sorting2
{
//declare an array of strings
static String[] nameArray = {"Alan", "Peter", "Ed", "Stephen", "Pheadraa"};
public static void main(String[] args)
{
// sorting by length
Arrays.sort(nameArray, new LengthCompare());
//print out elements of array
System.out.println(Arrays.toString(nameArray));
//count the number of elements in the array
int counter=nameArray.length;
//print out numeric number of elements in array
System.out.println("Number of elements in array: " + counter);
//print out sorted array with shortest first and longest last
printRuleAndArray("Sorted list by name length:");
}
Arrays.sort() will always sort the array you pass into it, it doesn't produce a fresh copy - so if you really need the unsorted array to hang around as well as the sorted array, then you'll have to make a copy of it:
String copyArr[] = new String[nameArray.length];
System.arraycopy( nameArray, 0, copyArr, 0, nameArray.length );
However, preferable to this approach (if feasible) would just be to do all the operations you need on the unsorted array (such as printing it or converting it to a string), then sort it afterwards.
As pointed out in the comment, Arrays.copyOf() could also be used to accomplish the same thing.
Arrays.sort will have altered your original array. Your choices are to either print your original array before sorting it, or to copy your original array and sort the copy.
Call String unsortedArr = Arrays.toString(nameArray); before array sorting, and when you need to print unsorted array just call System.out.println(unsortedArr);
Arrays.sort() sorts the array you pass into it. If you would like the original array later, copy the array first and then sort that array.
for(String arr : nameArray ) { //arr gets successively each value in nameArray.
System.out.println(arr);
}
this example is using foreach loop
Do something like this
String orig = Arrays.toString(nameArray);
Arrays.sort(nameArray, new LengthCompare());
String sorted = Arrays.toString(nameArray);
System.out.println(orig);
System.out.println(sorted);
Related
I am new to Java and Here is my code.
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
String[] onedata={"j","k","l"};
the thing I want to do here is that, I want to append the onedata into datas at last index value.
Please help let me know that how can I do this.
You can use an ArrayList because their sizes are mutable. For example:
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
List<String[]> datasList = new ArrayList<>(Arrays.asList(datas));
String[] onedata = {"j","k","l"};
datasList.add(onedata);
datas = datasList.toArray(new String[datasList.size()][]);
The things you are dealing with are arrays (String[]) and multidimensional arrays (String[][]) in Java, not lists. Their length is fixed. Therefore to append a new item to an array in such way that the length increases (so not by replacing the last item in the current array) you would need to create a new array with length n+1, assign the old values to the first n indices and then the new value to the index n+1.
Here I want to takes in the array of the object to sort and also the number of objects in the array.
public BookRecord [] sortString(BookRecord [] myArray, int noRecords)
Like I have tag values ABEW2345, HGNH4567, HJKG2342 in the .txt file. My question is how to implement the selection sort algorithm in this method to sort the object array?
The only thing I know is after the file was read, the array of BookRecord objects has been created, call the sortString() method. This method would use selection sorting algorithm to re-arrange the objects in the array in a lexicographic increasing order in respect of the tag values.
based on my understanding I suggest
public BookRecord[] sortString(BookRecord [] myArray, int noRecords)
{
//uses sort method of Arrays and simply returns the sorted array
Arrays.sort(myArray);
return myArray
}
after sorting, to view the values create a for loop to iterate over the Array.
public void viewBookRecord(BookRecord[] array)
{
for(int i = 0; i<array.length();i++){
System.out.print(array[i])
}
Quick overview of our assignment:
User needs to enter grades received. We do not know how many grades user needs to enter. If the user enters "-1" thats when we know the user is done entering grades.
Problem is how do you use a counter and assign values to an array in the same loop? I would rather not have to ask the user to enter all values twice (Once to get array size and the second time to assign grades to index positions).
Our professor gave us a handout that tells us to basically guess the size of the array and hope for the best. I refuse to believe that's the only solution.
Any help would be appreciated. Thanks.
You can't make dynamic array in java.
For that you will have to use List or ArrayList.
We will have to provide the size of array before application run or at coding time, while arrayList gives us facility to add data while we need it, so it's size will automatically increased when we add data.
Example :
import java.util.*;
public class ArrayListDemo {
public static void main(String args[]) {
// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
this example is from here.
UPDATE :
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that belong to List class. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList specific methods and use ArrayList specific members in addition to those inherited from List.
List is not a class it is an interface. It doesn't have any methods implemented. So if you call a method on a List reference, you in fact calling the method of ArrayList in both cases.
Using some kind of List is a better choice, as it basically does what you want (can grow and shrink), in fact, ArrayList is just that, a dynamic array.
You can hand roll your own if you can't use a List using System.arraycopy
For example, this will grow or shrink an array to match the size you provide...
public String[] updateArray(String[] src, int size) {
String[] dest = new String[size];
if (size > src.length) {
System.arraycopy(src, 0, dest, 0, src.length);
} else {
System.arraycopy(src, 0, dest, 0, size);
}
return dest;
}
Again... List is easier...
Building a dynamic array involves these basic steps:
-Create an array of a fixed capacity.
-When the size of the array (# of elements added) approach the capacity, create a new array (usually doubling the capacity), and copy all the old elements to the new array.
A linked list is the most efficient for your task of building the array (done in O(1) time). However, accessing elements for inserting and deleting in a linked list is not efficient (O(n) time). Imagine having to move through the whole list to get to the last element. Building the dynamic array is less efficient, because of the need to re-size the array as it grows. Inserting and deleting elements is less efficient because of need to move all the elements after to make room or fill the gap. However accessing an element in an array is efficient (O(1) time) and there are big advantages when it comes to sorting.
The Java ArrayList is an implementation of a dynamic array. You could also implement your own.
If you can't use an ArrayList, or any kind of dynamic list at all, then one solution would be this:
StringBuilder sb = new StringBuilder();
Scanner scanner = new Scanner(System.in);
int j;
while((j=scanner.nextInt()) !=-1){
sb.append(j + " ");
}
String []numbers = sb.toString().split(" ");
int[] grades = new int[numbers.length];
for(int i=0;i<numbers.length;i++){
grades[i] = Integer.parseInt(numbers[i]);
}
As you can see, I'm putting the input in a stringbuilder object, then I parse it in an array of strings, and convert that array in an integer array.
I hope this helps.
I know that the code to turn an arraylist into an array is:
private String[] arrayLst_to_array(ArrayList<String> al) {
String[] arr = new String[al.size()];
arr = al.toArray(arr);
return arr;
}
But I want my new array to have a certain string in the beginning and then after that, I want the rest of the arraylist.
I know that I could just add the string that I want to the beginning of the arraylist and then convert it, but is there a more efficient way?
You can use System.arraycopy():
String[] arr = new String[al.size() + 1];
arr[0] = someStr; // initial string
// copy the list:
System.arraycopy(al.toArray(), 0, arr, 1, al.size());
return arr;
A memory efficient but maybe not so well performing solution would be:
public static String[] listPlusOne(final ArrayList<String> list, final String prepend)
{
final String[] arr = list.toArray(new String[list.size() + 1]);
System.arraycopy(arr, 0, arr, 1, list.size());
arr[0] = prepend;
return arr;
}
This solution allocates only one String array and performs a memory move using System.arrayCopy() to move all the elements one position up.
Generally speaking memory moving is always not the best solution. A LinkedList will allow pretty quick element prepending, but has O(n) complexity when accessing elements at random positions. The ArrayList is slower on prepending (memory moving, reallocation) but has O(1) when accessing elements.
So, either you use something like the code above, or you prepend the element to the list.
If you add an item to the beginning of the list, the contents of the entire list have to be moved one position up. This means each element is touched twice in the entire operation. If you export the list to an array and then use System.arrayCopy to make room for one in the beginning, again each item is touched twice.
The easiest solution that touches each item only once seems to be creating the array, adding the string, and then iterating over the list to add its elements.
String[] arr = new String[al.size() + 1];
arr[0] = someStr;
int i=1;
for (String s: al) {
arr[i++] = s;
}
Whether this is faster than the approaches that iterate over the items twice but benefit from the efficiency of System.arrayCopy should be shown by benchmarks.
In Short Answer to your question is No.The Option you gave i believe is the best way to do it.
I have 2 arrays of data in Java. Based on the order of first array I have to sort the next array.
E.g -
String[] Array1 = {"EUROPE","MIDDLEEAST","OTHERs","AUSTRALIA"};
String[] Array2 = {"MIDDLEEAST","EUROPE","AUSTRALIA","OTHERs","ASIA","EUROPE"};
My output should look like:
{"EUROPE","EUROPE","MIDDLEEAST","OTHERs","AUSTRALIA","ASIA"}
What is the best way to do it?
To sort you need to define a sorting order so given element A and B, you can determine easily if A should go before or after B in the sorted list.
This concept is formalized with the concept of a Comparator in Java.
In this case the sorting order is defined by the order of the elements in a list. The simplest approach is given A and B to find each of them in the original list, note the index found, and compare the indexes to find out which one goes first.
Depending on the size of your data this might be too slow. You can then create a HashMap<String,Long> which holds the index of a given string in Array1. Here it would hold "DEF"->0, "ABC"->1, "XYZ"->2.
May be this:
1) Sort both of them.
2) Create blank result table
3) Take first elem from sorted Array2 and put it to result table with the original index of the first elem on sorted Array1
3) Repeat the step 3 on the second element and so on.
The computational complexity would be like sorting method used: O(nlogn) for quicksort
You can definitely do this in O(n log n). But the best approach depends on what is more important: quick, clean code or not allocating extra memory.
If you don't care about using extra memory, you can allocate a separate array, where each element is a pair:
public class Pair implements Comparable {
...
}
Then you would sort the array of pairs using Arrays.sort(Object[]).
If you don't want to allocate quite so much space, you can use an auxiliary array that contains the indexes in Integer form:
final String[] array1 = ...;
final String[] array2 = ...;
assert array1.length == array2.length;
Comparator<Integer> c = new Comparator<Integer> {
int compare(Integer a, Integer b) {
return array1[a].compareTo(array1[b]);
}
};
Integer[] aux = new Integer[array1.length];
for (int i = 0; i < aux.length; ++i) { aux[i] = i; }
Arrays.sort(aux, c);
String[] result = new String[array1.length];
for (int i = 0; i < aux.length; ++i) {
result[i] = array2[aux[i]];
}
If you are trying to do the entire thing in-place and not allocate additional memory, then you will need to implement one of the n-log-n sort algorithms yourself...
There are (at least) two ways to sort one array and reorder a second array so corresponding elements still match. Both require constructing a third array and writing a custom comparison function.
Method 1
Define a custom object that contains one element of each array. (In your case, it might be a two-element String array.) Write a comparator (or implement Comparable) for the custom object that simply compares the elements from the first array. Build an array of the custom objects from the two input arrays, sort the third array, and then extract the results.
This is the method most commonly recommended for this problem.
Method 2
Construct an array of Integer indexes initialized to 0, 1, 2, ..., n-1 (where n == Array1.length). Sort the index array using a comparator that compares indexes by comparing the Array1 elements that they index.
The second method will be faster and will not require as much object construction.
Two other ideas:
Could these values be an enum rather than a set of strings? The natural order of an enum is the order of declaration, so Arrays.sort() would just work.
Helper code exists in Guava's Ordering.explicitOrder(List):
String[] explicitOrder = {"EUROPE", "MIDDLEEAST", "OTHERs", "AUSTRALIA"};
String[] toSort = ...
Comparator<String> comparator = Ordering.explicit(Arrays.asList(explicitOrder));
String[] sorted = Arrays.sort(toSort, comparator);