How to sort an ArrayList - java

All I need is the simplest method of sorting an ArrayList that does not use the in-built Java sorter. Currently I change my ArrayList to an Array and use a liner sorting code, but I later need to call on some elements and ArrayLists are easier to do that.

you can use anonymous sort.
Collections.sort(<ArrayList name>, Comparator<T>() {
public int compare(T o1, T o2) {
.....
....
}
});
where T is the type you want to sort (i.e String, Objects)
and simply implement the Comparator interface to your own needs

Assuming an ArrayList<String> a...
Easiest (but I'm guessing this is what you're saying you can't use):
Collections.sort(a);
Next easiest (but a waste):
a = new ArrayList<String>(new TreeSet<String>(a));

Assuming "in-built sort" refers to Collections.sort() and you are fine with the sorting algorithm you have implemented, you can just convert your sorted array into an ArrayList
ArrayList list = new ArrayList(Arrays.asList(sortedArray));
Alternatively, you can rewrite your sorting algorithm to work with a List (such as an ArrayList) instead of an array by using the get(int index) and set(int index, E element) methods.

Sorting Arguments passed through Command prompt; without using Arrays.sort
public class Sort {
public static void main(String args[])
{
for(int j = 0; j < args.length; j++)
{
for(int i = j + 1; i < args.length; i++)
{
if(args[i].compareTo(args[j]) < 0)
{
String t = args[j];
args[j] = args[i];
args[i] = t;
}
}
System.out.println(args[j]);
}
}
}
By using Array.sort
import java.util.*;
public class IntegerArray {
public static void main(String args[])
{
int[] num=new int[]{10, 15, 20, 25, 12, 14};
Arrays.sort(num);
System.out.println("Ascending order: ");
for (int i=0; i<num.length; i++)
System.out.print(num[i] + " ");
}
}

Collections.sort(List);

If i remember correctly when you pull an element out of the middle of an arrayList it moves the rest of the elements down automaticly. If you do a loop that looks for the lowest value and pull it out then place it at the end of the arrayList. On each pass i-- for the index. That is use one less. So on a 10 element list you will look at all 10 elements take the lowest one and append it to the end. Then you will look at the first nine and take the lowest of it out and append it to the end. Then the first 8 and so on till the list is sorted.

Check for Comparator in java. You can implement your own sorting using this and use Collections.sort(..) to sort the arraylist using your own Comparator

If you are meant to sort the array yourself, then one of the simplest algorithms is bubble sort. This works by making multiple passes through the array, comparing adjacent pairs of elements, and swapping them if the left one is larger than the right one.
Since this is homework, I'll leave it to you to figure out the rest. Start by visualizing your algorithm, then think about how many passes your algorithm needs to make, and where it needs to start each pass. Then code it.
You also need to understand and solve the problem of how you compare a pair of array elements:
If the elements are instances of a primitive type, you just use a relational operator.
If the elements are instances of reference types, you'll need to use either the Comparable or Comparator interface. Look them up in the javadocs. (And looking them up is part of your homework ...)

Here is a "simple" quicksort implementation:
public Comparable<Object>[] quickSort(Comparable<Object>[] array) {
if (array.length <= 1) {
return array;
}
List<Comparable<Object>> less = new ArrayList<Comparable<Object>>();
List<Comparable<Object>> greater = new ArrayList<Comparable<Object>>();
Comparable<Object> pivot = array[array.length / 2];
for (int i = 0;i < array.length;i++) {
if (array[i].equals(pivot)) {
continue;
}
if (array[i].compareTo(pivot) <= 0) {
less.add(array[i]);
} else {
greater.add(array[i]);
}
}
List<Comparable<Object>> result = new ArrayList<Comparable<Object>>(array.length);
result.addAll(Arrays.asList(quickSort(less.toArray(new Comparable<Object>[less.size()]))));
result.add(pivot);
result.addAll(Arrays.asList(quickSort(greater.toArray(new Comparable<Object>[greater.size()]))));
return result.toArray(new Comparable<Object>[result.size()]);
}
The last operations with arrays and list to build the result can be enhanced using System.arraycopy.

Related

Finding the duplicates in the array

So here is this function that has 2 arguments given that is the array and the size of array and we have to return the answer in form of Arraylist.
I wrote this code but it was giving me time limit exceeded error and I was solving this as a problem on geeksforgeeks but I am not getting why is it giving time limit exceeded error. Thank you!
public static ArrayList<Integer> duplicates(int arr[], int n) {
Arraylist<Integer> arrList = new ArrayList<>();
Arrays.sort(arr);
for(int i=0; i<n; i++) {
if(arr[i] == arr[i+1] && !arrList.contains(arr[i])) {
arrList.add(arr[i]);
}
}
if(arrList.isEmpty()) {
arrList.add(-1);
}
return arrList;
}
I think expected time complexity to solve this problem is o(n) but you used sorting that's why its time complexity is o(nlogn). so you can use Treemap (which stores values in sorted order) to solve this problem in o(n) time complexity.
class Solution {
public static ArrayList<Integer> duplicates(int arr[], int n) {
TreeMap <Integer,Integer> map= new TreeMap<>();
ArrayList <Integer> ans= new ArrayList<>();
for(int i=0;i<n;i++){
map.put(arr[i],map.getOrDefault(arr[i],0)+1);
}
for(int key : map.keySet()){
if(map.get(key)>1){
ans.add(key);
}
}
if (ans.size()==0){
ans.add(-1);
return ans;
}
return ans;
}
}
You don't need sort as sorting has higher complexity O(nlog(n)).
Not sure what are the constraints and instructions for this question, but if you really don't have problem using extra space, you can use another array list, navigate through all the elements in the arr and put it to the some list called temp and check if number is already in the temp . Code reference is given below :
List<Integer> result = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
int n = arr.length; // or you already passed n
for(int i=0;i<n;i++){
if(!temp.contains(arr[i])) {
temp.add(arr[i]);
}
else {
result.add(arr[i]);
}
}
return result;
This will be done at O(n) for both time and space complexity.
Of course, if you want to achieve the result without using extra space, you've to use another approach.
Condition arr[i] == arr[i+1] would cause an exception during the last iteration step (when i=n-1) with 100% certainty because i+1 will refer to the index that doesn't exist. You need to get rid of it.
contains() check on a List is expensive, it has O(n) time complexity. Which results in the overall quadratic O(n^2) time complexity of your solution.
As #Scary Wombat has pointed out in the comment, you can use HashSet to check whether the element was previously encountered or not. It would also eliminate the need for sorting the data and time complexity of the solution would be linear O(n).
In case if you have a requirement the result should be sorted, then it'll be more efficient to sort the resulting list (because it would contain fewer data than the given array).
public static List<Integer> duplicates(int[] arr, int n) {
Set<Integer> seen = new HashSet<>();
List<Integer> duplicates = new ArrayList<>();
for (int i = 0; i < n; i++) {
int next = arr[i];
if (!seen.add(next)) {
duplicates.add(next);
}
}
if (duplicates.isEmpty()) {
duplicates.add(-1);
}
// duplicates.sort(null); // uncomment this Line ONLY if results required to be in sorted order
return duplicates;
}
Sidenotes:
Don't use concrete classes like ArrayList as a return type, type of variable, method parameter, etc. Leverage abstractions, write the code against interfaces like List, Set, etc. If coding platform wants you to return an ArrayList, that unfortunate - leave the type as is, but keep in mind that it's not the way to go. See What does it mean to "program to an interface"?
Avoid using C-style of array declaration int arr[]. Because it mixes the variable name and the type, which might look confusing. int[] arr is preferable.

Reverse order of the Arrays stored in ArrayList

I'm working with Processing and IGeo library and I have an ArrayList of IVec[] arrays:
ArrayList<IVec []> v = new ArrayList<IVec[]>();
For every I of the ArrayList I have a collection of IVec [] arrays that represent the coordinates of the control points of a curve. I need to reverse the order of the IVec [] control points keeping the same order of the ArrayList (I'm trying to invert curve seam reversing control points order and keeping the original order of the curves) but I can't understand how to do this.
Can anyone help me?
I won't provide you a full solution, but will guide you through it:
Iterate on the array list v
for each item in it (IVec[]),
Convert the array to a collection (for example using Arrays.asList)
Use Collections.reverse to reverse the items in the list
Conver it back to an array
You can use Collections.reverse
You can also use a stack data structure. You can iterate over collection you wish to reverse by pushing the elements into the stack. Then, when you actually want to use the elements, you pop each element from the stack, which will allow you to iterate over the collection in reverse order.
This solution is working:
for (int i=0; i<v.size (); i++) {
IVec [] vert=v.get(i);
for (int j=0; j<vert.length/2; j++) {
IVec temp = vert[j];
vert[j]=vert[vert.length -1 - j];
vert[vert.length - 1 - j] = temp;
}
}
Try this;
Create a Helper method/function that takes and returns array.
Inside the Helper method, use Collections.reverse
return the reversed array.
call this helper method inside a loop as below:
for(int i = 0; i < OutArray.length; I++)
{ // Here get the inner Array and pass it to Helper method.
// Add the return array to newArray List
}
return newArrayList.
This should work (not the most efficient way, but easily understood):
public static <T> void reverseElements(ArrayList<T[]> list) {
ArrayList<T> tempList = new ArrayList<T>();
for(T[] arr : list) {
tempList.clear();
for(T t : arr)
tempList.add(t);
Collections.reverse(tempList);
tempList.toArray(arr);
arr = tempList.toArray(arr);
}
}

Java - Sort a multidimensional double array

I have a multidimensional array with double values that I would like to sort..
//declare array
standingsB = new Double[10][2];
//populate array from the temparray created during read from file
arryLgt = 0;
for (int row = 0; row < standingsB.length; row++){
for (int column = 0; column < standingsB[row].length; column++) {
standingsB[row][column] = Double.parseDouble(tempStandingsArray[arryLgt]);
arryLgt = arryLgt + 1;
}
}
The array has values such as [1.5,7.0] [4.2,4.0] etc...
For the next part I don't really know how it works but from reading other articles here this is the best as I can copy without knowledge
Arrays.sort(standingsB, new Comparator<Double[]>() {
#Override
public int compare(Double[] s1, Double[] s2) {
compare(s1, s2);
}
});
The above fails to compile (with missing return statement) which is to be expected as I have no idea on how to use the Arrays.sort with a comparator. But I'm not even sure if I'm on the right page being as new to Java (and programing in general) as I am.
Thanks for looking!
You're pretty close. Your comparator will depend on what order you want your results in. Let's say you want the rows to be sorted in the natural order of the first element in each row. Then your code would look like:
Arrays.sort(standingsB, new Comparator<Double[]>() {
public int compare(Double[] s1, Double[] s2) {
if (s1[0] > s2[0])
return 1; // tells Arrays.sort() that s1 comes after s2
else if (s1[0] < s2[0])
return -1; // tells Arrays.sort() that s1 comes before s2
else {
/*
* s1 and s2 are equal. Arrays.sort() is stable,
* so these two rows will appear in their original order.
* You could take it a step further in this block by comparing
* s1[1] and s2[1] in the same manner, but it depends on how
* you want to sort in that situation.
*/
return 0;
}
}
};
I think the answer provided by #Tap doesn't fulfill the askers question to 100%. As described, the array is sorted for its value at the first index only. The result of sorting {{2,0},{1,2},{1,1}} would be {{1,2},{1,1},{2,0}} not {{1,1},{1,2},{2,0}}, as expected. I've implemented a generic ArrayComparator for all types implementing the Comparable interface and released it on my blog:
public class ArrayComparator<T extends Comparable<T>> implements Comparator<T[]> {
#Override public int compare(T[] arrayA, T[] arrayB) {
if(arrayA==arrayB) return 0; int compare;
for(int index=0;index<arrayA.length;index++)
if(index<arrayB.length) {
if((compare=arrayA[index].compareTo(arrayB[index]))!=0)
return compare;
} else return 1; //first array is longer
if(arrayA.length==arrayB.length)
return 0; //arrays are equal
else return -1; //first array is shorter
}
}
With this ArrayComparator you can sort multi-dimensional arrays:
String[][] sorted = new String[][]{{"A","B"},{"B","C"},{"A","C"}};
Arrays.sort(sorted, new ArrayComparator<>());
Lists of arrays:
List<String[]> sorted = new ArrayList<>();
sorted.add(new String[]{"A","B"});
sorted.add(new String[]{"B","C"});
sorted.add(new String[]{"A","C"});
sorted.sort(new ArrayComparator<>());
And build up (Sorted)Maps easily:
Map<String[],Object> sorted = new TreeMap<>(new ArrayComparator<>());
sorted.put(new String[]{"A","B"}, new Object());
sorted.put(new String[]{"B","C"}, new Object());
sorted.put(new String[]{"A","C"}, new Object());
Just remember, the generic type must implement the Comparable interface.
Solution with lambda sorting array of int[][] contests example :
Arrays.sort(contests, (a, b)->Integer.compare(b[0], a[0]));
Arrays.sort() expects a single dimensional array while in your case you are trying to pass a multidimensional array.
eg
Double[] d = {1.0,5.2,3.2};
Then you use Arrays.sort(d) since the sort can work on the primitive types or the wrapper types.

How can I dynamically add items to a Java array?

In PHP, you can dynamically add elements to arrays by the following:
$x = new Array();
$x[] = 1;
$x[] = 2;
After this, $x would be an array like this: {1,2}.
Is there a way to do something similar in Java?
Look at java.util.LinkedList or java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.
A bit similar to the PHP behaviour is this:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Then you can write:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).
The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.
If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)
Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.
Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:
/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between array and arraylist.
The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
Convert array to an arraylist
Add element to the arrayList
Convert back the new arrayList to the array
Here is the simple picture of it
And finally here is the code:
Step 1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Step 2:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Step 3:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Step 4
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.
See: Java List Tutorial
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.
This Collection framework will be available in "java.util.*" package
For example if you use ArrayList,
Create an object to it and then add number of elements (any type like String, Integer ...etc)
ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");
Now you were added 3 elements to an array.
if you want to remove any of added elements
a.remove("suman");
again if you want to add any element
a.add("Gurram");
So the array size is incresing / decreasing dynamically..
Use an ArrayList or juggle to arrays to auto increment the array size.
keep a count of where you are in the primitive array
class recordStuff extends Thread
{
double[] aListOfDoubles;
int i = 0;
void run()
{
double newData;
newData = getNewData(); // gets data from somewhere
aListofDoubles[i] = newData; // adds it to the primitive array of doubles
i++ // increments the counter for the next pass
System.out.println("mode: " + doStuff());
}
void doStuff()
{
// Calculate the mode of the double[] array
for (int i = 0; i < aListOfDoubles.length; i++)
{
int count = 0;
for (int j = 0; j < aListOfDoubles.length; j++)
{
if (a[j] == a[i]) count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = aListOfDoubles[i];
}
}
return maxValue;
}
}
This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.
int [] test = {12,22,33};
int [] test2= new int[test.length+1];
int m=5;int mz=0;
for ( int test3: test)
{
test2[mz]=test3; mz++;
}
test2[mz++]=m;
test=test2;
for ( int test3: test)
{
System.out.println(test3);
}
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
package simplejava;
import java.util.Arrays;
/**
*
* #author sashant
*/
public class SimpleJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String[] transactions;
transactions = new String[10];
for(int i = 0; i < transactions.length; i++){
transactions[i] = "transaction - "+Integer.toString(i);
}
System.out.println(Arrays.toString(transactions));
}catch(Exception exc){
System.out.println(exc.getMessage());
System.out.println(Arrays.toString(exc.getStackTrace()));
}
}
}

Java: Sorting unsorted array in descending order

I have an unsorted array of objects. I need to know how I can sort my array in descending order, according to the highest value inside the objects.
I need to do this using for loops, not the easy way.
I had done this but it seems there is a problem:
student[] temp=new student[s.length];
for (int i=0;i<s.length;i++)
{
if (s[i].GetGpa() > s[i + 1].GetGpa())
{
temp[i] = s[i];
}
}
How should I do it using for loops?
This should get you started. You'll need to create your own Comparator and then call Collections.Sort().
Collections.sort(List<T> list, Comparator<? super T> c)
I suggest looking at the Wikipedia article for sorting algorithms. Your code fails because you compare each element only with the next one - but that's not a sorting algorithm at all, because in order to be correctly placed in the first position, an element needs to be bigger than all other elements, not just the next one.
Also, Using a lowercase class name is very much against Java coding standards.
public class Student implements Comparable { ... }
Arrays.sort(students);
List<Object> list = Arrays.asList(students);
Collections.reverse(list);
students = list.toArray();
for (int j=0;j<s.length;j++) {
for (int i=0;i<s.length - 1 - j;i++)
{
if (s[i].GetGpa() > s[i + 1].GetGpa())
{
student temp = s[i];
s[i] = s[i+1];
s[i+1] = temp;
}
}
}
for(int i=0;i<s.length;i++)
{
for(int j=i+1;j<s.length;j++)
{
if(s[j].GetGpa()>s[i].GetGpa())
{
student[] temp=new student[5];
temp[j]=s[j];
s[j]=s[i];
s[i]=temp[j];
}
}
}

Categories

Resources