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];
}
}
}
Related
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.
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);
}
}
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.
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.
I'm trying to find minimum of an array. The array contain Nodes - a node contains of an element E and a priority int. Im want to find the Node in the array with the smallest priority.
#Override
public E min() {
Node temp = S[0];
for(int i = 1; i<S.length; i++){
int prio= S[i].getPrioritet(); <-- nullpointer excp.
if(prio<temp.getPrioritet()){
temp = S[i];
}
}
return temp.getElement();
But i get an nullpointer exception when i try to use it. Does anybody know what im doing wrong?
Here is my test:
PrioritetArraySorteret<String> p = new PrioritetArraySorteret<String>();
p.insert(1, "Hello");
p.insert(3, "Hi");
p.insert(4, "Hawdy");
System.out.println(p.min());
}
start with i=0 as the array is indexed
for(int i = 0; i<S.length; i++){
int prio= S[i].getPrioritet(); <-- nullpointer excp.
if(prio<temp.getPrioritet()){
temp = S[i];
}
}
It simply means that the element at one of the indexes of array S is null. Maybe you're initialized the array at a size n but filled in less than n positions.
Altering like this will probably fix it:
for(int i = 1; i<S.length; i++){
if(S[i] != null) {
int prio= S[i].getPrioritet(); <-- nullpointer excp.
if(prio<temp.getPrioritet()){
temp = S[i];
}
}
}
That said, you might be reinventing the wheel here a bit. Using a simple ArrayList parameterized with some type that you define which encapsulates a value and priority would do. You could then have that type implement Comparable with a compareTo method that uses the priority, or write a Comparator to use for finding the minimum:
List<YourType<String>> list = new ArrayList<YourType<String>>();
Collections.min(list);
Or, if you're using a custom Comparator:
Collections.min(list, yourComparator);
-- edited for min instead of sort. Sorry.
The array S has not been initialized or one/more elements has been initialized.