arraylist.get(i)= arraylist.get(i);
arraylist.get(j) =tmp;
You can't assign a value to a method call. As the compiler told you, the left hand side of an assignment must be a variable.
Use set method :
arraylist.set(i,arraylist.get(j));
arraylist.set(j,tmp);
Is there a way to do it without using set method?
No. Unless you wish to convert your ArrayList to an array, sort the array, and update the ArrayList with the sorted array.
Answer from Eran on Stack Overflowarraylist.get(i)= arraylist.get(i);
arraylist.get(j) =tmp;
You can't assign a value to a method call. As the compiler told you, the left hand side of an assignment must be a variable.
Use set method :
arraylist.set(i,arraylist.get(j));
arraylist.set(j,tmp);
Is there a way to do it without using set method?
No. Unless you wish to convert your ArrayList to an array, sort the array, and update the ArrayList with the sorted array.
Integer[] list={3,5,100,8,17,19};
for(int i=0;i<list.length;i++){
for(int j=i+1;j<list.length;j++){
Integer tempI=list[i];
Integer tempJ=list[j];
if(tempI>tempJ){
list[i]=tempJ;
list[j]= tempI;
}
}
}
for(Integer a:list){
System.out.println(""+a);
}
java - Sorting a list without using the Collection methods - Stack Overflow
How can I get Sorted List behavior in Java without using Collections.sort()? - Stack Overflow
Sorting array list without using .sort in Java
How can I sort an arrayList containing objects without using a sort method from the java collections library?
The roadmap
- Wikipedia/Sorting algorithm
- Simple quadratic algorithms
- Bubble sort - beginner friendly
- Selection sort - very intuitive
- Insertion sort - also intuitive
- Essential comparison-based sort
- Merge sort - slightly more advanced
- Quick sort - skip this for now, but watch for it later
- Essential non-comparison sort
- Counting sort - important to understand
- Simple quadratic algorithms
Your first sorting algorithm
I think counting sort is the best algorithm to start with. Read up about it and try to understand it, then write your own implementation as follows:
- Generate 1000 random numbers between 0..9 (use
java.util.Randomto populateint[]) - Sort them using counting sort.
Once you do this, you'll realize how simple sorting can be when you can take advantage of certain properties of the numbers (in this case, the fact that they're between 0..9).
Your second sorting algorithm
Selection sort is a good intuitive sorting algorithm for your next implementation. It's a comparison sort, and doesn't assume anything about the range of the numbers. Many people in real life sort using this algorithm:
- Given some selection to choose from, we look for the best and pick it first.
- Now the best is out, so we look for the second best from the rest.
- Then we look for the third best... etc
The rest of the journey
You may want to implement the other quadratic algorithms just to get a good grasp on the basics, but the next step would be to learn recursion, specifically divide and conquer algorithms.
You would not want to dive straight into merge sort/quick sort without first understanding basic recursion, because it can get too overwhelming.
Do the usual recursion exercises, factorial, Fibonacci, etc. Ask for pointers from stackoverflow if you need guidance. There may even already be questions with good answers about learning recursion.
A side trip
You may want to implement the merge portion of merge sort, even before you fully understand recursion yet. It's a very educational exercise:
- Given a sorted array of numbers A and a sorted array of numbers B, merge the two into one sorted array
- Take advantage of the fact that A and B are already sorted
Since this is most likely homework I am going to give you advice rather than source code.
Take a look at this page on sorting algorithms. You should choose the correct sorting algorithm based on your requirements. Choosing the wrong algorithm can mean poor performance or unnecessary complexity.
Assuming you have only a small number of items and want a simple algorithm then you could look at insertion sort. The Wikipedia page includes pseudocode. This algorithm has O(n^2) performance.
If your lists are quite long and you want better performance at the cost of a slightly more complicated algorithm, you could try merge sort. This algorithm has O(n log(n)) performance both average and worst case and is a popular choice in language libraries.
It's hard to get O(1) indexing and O(log n) insertion/deletion in the same data structure. O(1) indexing means we can't afford the link-following involved in indexing a tree, list, skip list, or other link-based data structure, while O(log n) modification means we can't afford to shift half the elements of an array on every insertion. I don't know if it's possible to fulfill these requirements simultaneously.
If we relax one of these requirements, things become much easier. For example, O(log n) for all operations can be achieved by an indexable skip list or a self-balancing BST with nodes that keep track of the size of the subtree rooted at the node. Neither of these can be built on top of the skip list or BST in Java's standard library, though, so you'd probably need to install another library or write your own data structure.
O(1) indexing, O(log n) search, and O(n) insert and delete can be done by keeping a sorted ArrayList and using Collections.binarySearch to search for elements or insert/delete positions. You never need to call Collections.sort, but you still need to call the ArrayList's O(n) insert and delete methods. This is probably the easiest option to build on top of Java's built-in tools. Note that with recent Java versions, Collections.sort is an adaptive mergesort that would take O(n) time to sort an array where only the last element is out of sorted order, so you could probably get away with relying on Collections.sort. However, that's an implementation detail that alternative Java implementations don't have to follow.
If your primary goal is O(1) for indexed lookup (get()), then you can implement your own class implementing List, backed by an array, using Arrays.binarySearch().
retrieve: get(int) - O(1) - array index
search: contains(Object) - O(log n) - binarySearch
indexOf(Object) - O(log n) - binarySearch
insert: add(E) - O(n) - binarySearch + array shift
delete: remove(int) - O(n) - array shift
remove(Object) - O(n) - binarySearch + array shift
The add(E) method is violating the List definition (append), but is consistent with the Collection definition.
The following methods should throw UnsupportedOperationException:
add(int index, E element)
addAll(int index, Collection<? extends E> c)
set(int index, E element)
If duplicate values are not allowed, which could be a logical restriction, consider also implementing NavigableSet, which is a SortedSet.
Hi so I made this method that should sort items by weight (descending order), but the tests aren't working can someone pls help? The first two assertEquals work but at the 3rd one the output my code gives is 2 but it should be 0 :
Expected :0
Actual :2
here's the assignment description:
Task 7: Item Storage
Your program should have an Item Bag to store items. An item bag has a maximum weight defined when creating the bag. The bag also stores a collection of items that begins empty when creating the bag. The maximum weight cannot change once the bag is created. You don’t need to write code to check if two bags are equal.
The bag should provide: the current number of items stored, the current weight of the bag, and its maximum weight. Other operations are defined below.
7.1 - Adding items to the bag:
The collection of items can accept repeated items and the items are stored in a specific sequence. When adding an item to the bag, the item must be placed in the index where its weight is higher than the items after them and lighter than those before (i.e., sorted by weight).
When adding an item to the bag, the method should return the index in which the item was added. If the bag cannot fit the item (it goes above the max weight), you should return -1.
Note: You don’t need to use Arrays.sort or Collections.sort for solving this task. In fact, using these sorting libraries can make your code inefficient.
public int addItem(Item item1) {
bagOfItems.add(item1);
int index = 0;
for (Item item : bagOfItems) {
if (item.weight < item1.weight) {
bagOfItems.set(bagOfItems.indexOf(item), item1);
bagOfItems.set(bagOfItems.indexOf(item1), item);
index = bagOfItems.indexOf(item1);
} else if (this.currentWeight >= this.maxWeight) {
index = -1;
}
} return index;
}
here's the test class:
@Test
public void shouldAddItemsCorrectly() {
Item potion1 = new Item("Potion", 20, 5.0);
Item potion2 = new Item("Potion", 20, 5.0);
Item potion3 = new Item("Potion", 20, 5.0);
Item hyperPotion = new Item("Hyper Potion", 50, 10.0);
Item superPotion = new Item("Super Potion", 40, 8.3);
ItemBag itemBag = new ItemBag(30.0);
assertEquals(0, itemBag.addItem(potion1));
assertEquals(0, itemBag.addItem(potion2));
assertEquals(0, itemBag.addItem(hyperPotion)); //the problem is here
assertEquals(1, itemBag.addItem(superPotion));
assertEquals(-1, itemBag.addItem(potion3));
assertEquals(4, itemBag.getNumOfItems());
assertEquals(28.3, itemBag.getCurrentWeight());
}
}I have this code I am working on for a homework assignment, but the professor has specified that we cannot use anything from java collections. The issue is that all of his examples use collections, and all of his examples about sorting only cover sorting an int array. The code I am writing has to sort the array by both "rollno"(the int variable assigned to each "student" object) and by "name"(the string variable assigned to each "student").
The assignment calls for the use of a selection sort method, so I want to sort the numbers in order from 1-10 and sort the names by string length. If anyone can guide me forward on this I would greatly appreciate it because I am lost on how to even begin a selection sort method.
Sidenote: The github has four files in it; "arrSort", "Student", "rollComp", and "nameComp". "arrSort" is the main method and is where I am trying to implement the sort method, "Student" is the object class, "rollComp" and "nameComp" are both comparator classes. All of these files are copied directly from my IDE, and if you notice ANY errors in how I have formatted anything, or if you have any other questions please let me know.
Hi so I made this method that should sort items by weight (descending order), but the tests aren't working can someone pls help? The first two assertEquals work but at the 3rd one the output my code gives is 2 but it should be 0 :
Expected :0
Actual :2
here's the assignment description:
Task 7: Item Storage
Your program should have an Item Bag to store items. An item bag has a maximum weight defined when creating the bag. The bag also stores a collection of items that begins empty when creating the bag. The maximum weight cannot change once the bag is created. You don’t need to write code to check if two bags are equal.
The bag should provide: the current number of items stored, the current weight of the bag, and its maximum weight. Other operations are defined below.
7.1 - Adding items to the bag:
The collection of items can accept repeated items and the items are stored in a specific sequence. When adding an item to the bag, the item must be placed in the index where its weight is higher than the items after them and lighter than those before (i.e., sorted by weight).
When adding an item to the bag, the method should return the index in which the item was added. If the bag cannot fit the item (it goes above the max weight), you should return -1.
Note: You don’t need to use Arrays.sort or Collections.sort for solving this task. In fact, using these sorting libraries can make your code inefficient.
public int addItem(Item item1) {
bagOfItems.add(item1);
int index = 0;
for (Item item : bagOfItems) {
if (item.weight < item1.weight) {
bagOfItems.set(bagOfItems.indexOf(item), item1);
bagOfItems.set(bagOfItems.indexOf(item1), item);
index = bagOfItems.indexOf(item1);
} else if (this.currentWeight >= this.maxWeight) {
index = -1;
}
} return index;
}
here's the test class:
@Test
public void shouldAddItemsCorrectly() {
Item potion1 = new Item("Potion", 20, 5.0);
Item potion2 = new Item("Potion", 20, 5.0);
Item potion3 = new Item("Potion", 20, 5.0);
Item hyperPotion = new Item("Hyper Potion", 50, 10.0);
Item superPotion = new Item("Super Potion", 40, 8.3);
ItemBag itemBag = new ItemBag(30.0);
assertEquals(0, itemBag.addItem(potion1));
assertEquals(0, itemBag.addItem(potion2));
assertEquals(0, itemBag.addItem(hyperPotion)); //the problem is here
assertEquals(1, itemBag.addItem(superPotion));
assertEquals(-1, itemBag.addItem(potion3));
assertEquals(4, itemBag.getNumOfItems());
assertEquals(28.3, itemBag.getCurrentWeight());
}
}Hey, this week I was introduced and working with lists and one task is to sort a list without using collections. The problem isn’t that I don’t know how to do it but rather that I think that my first intuition doesn’t seem like a good approach.
The first thing that came to my mind would be to loop over the list to count the length, then create a new array and then loop again over the list to copy the values into the array. Then I would insertionSort the array and then create a new list and lastly change the head to point at the new list.
All in all, I’m pretty sure this should work and shouldn’t be too hard but it seems like too many extra steps and thus creating ugly code.
So do you have any other solutions how I could approach that problem?
So i have an arraylist where each index contains a book which consists of two strings, Author and Title.
How do i sort the list by authors alphabetically?
Any suggestions are appriciated, thanks!