-1

I am very new with list and such and am currently trying to learn them. I made a program using them and everything worked perfectly until i didn´t get to sorting numbers inside of the list. Now whenever I got to this part of the code it just stopped working:

if ((st.get(i))>(st.get(k))) {
    int temp=st.get(k);
    st.add(k,st.get(i));
    st.add(i,temp);
}

Could you help me with what I did wrong and how to fix it?

Xxy
  • 3
  • 2
  • java 8 -> `st.sort(Comparator.naturalOrder());` – Mohsen Dec 08 '18 at 21:19
  • your question is not well described you can use Collections.sort(yourList); to do so, like in this question if a have understood what you mean https://stackoverflow.com/questions/20518078/how-to-sort-listinteger – Lho Ben Dec 08 '18 at 21:19
  • 1
    Not sure what you mean with "stopped working", but you are not swapping elements in the list, but adding _more_ elements. Try `set(index, element)` instead of `add(index, element)`. Hard to tell if this is the only problem, though. – tobias_k Dec 08 '18 at 21:23
  • Collections.sort(st) should sort your List. – uncleBounty Dec 08 '18 at 21:29

2 Answers2

0

Your problem description "just stopped working" is a bit vague. I am assuming that you are not getting an exception but just an incorrect output. The problem with (this part of) your code is that you are not swapping the misplaced elements in the list, but adding copies of those elements at the respective indices. Instead of add(index, element) you should use set(index, element).

if (st.get(i) > st.get(k)) {
    int temp = st.get(k);
    st.set(k, st.get(i));
    st.set(i, temp);
}

Of course, there might be other problems in the remainder of your sort function. Also, as noted in comments, while implementing your own Bubble Sort or Selection Sort or whichever this is is a great exercise, in all practical applications you should use one of the several built-in sorting methods instead, such as Collections.sort.

tobias_k
  • 81,265
  • 12
  • 120
  • 179
0

If you would like to use Java 8 there is a simple way to sort nums in an List of Integers. Here is an example one of many.

public class Main {

    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(1, 4, 5, 29, 30, 11, 2, 6);
        nums.sort(Comparator.naturalOrder());
        System.out.println(nums);
    }
}
Reddi
  • 677
  • 6
  • 19
  • Why limit this to Java 8? There are builtin sort methods well before that, although not that particular one. Also, we are currently at Java 11, with Java 8 being the oldest still supported version, so that note might not actually be needed anymore, anyway. – tobias_k Dec 08 '18 at 22:33
  • I just gave an simple example of it quickly. Of course you have right, there are many sort methods. – Reddi Dec 08 '18 at 22:39