I'm given a List<Integer>
and I'm trying to return the 2 smallest integers in the List in a new array.
To do this, I have created a helper that finds the smallest number in the array and then used that in my main function, where I hope to use a while loop that runs until 2, since I need the 2 smallest numbers, and remove the first (smallest) number in order to find the next smallest number and then add them to the new array I made.
Here is my code:
public static int countSorthelper(List<Integer> arr) {
int temp = 0;
int n = 0;
while(n <= 2){
for (int x = 0; x < arr.size(); x++){
for (int y = x+1; y < arr.size() && y <= x+y; y++){
if(arr.get(y) > arr.get(x)){
temp = arr.get(x);
n++;
}
}
}
}
return temp;
}
public static List<Integer> countSort(List<Integer> arr){
int n = 0;
List<Integer> j = new ArrayList<>();
while (n <= 2){
countSorthelper(arr);
arr.remove(countSorthelper(arr));
j.add(countSorthelper(arr));
n++;
}
return j;
}
When I try to run this, the output terminates due to too much running time, what changes do I need to make in my code??