Peter Cao
Milo Chang
/** Returns if the ArrayList is sorted in ascending order
*/
public static boolean isSorted(ArrayList<Integer> array) {
for (int i = 0; i < array.size() - 1) {
if (array.get(i + 1) < array.get(i)) { //checks if two array elements are in the
return false; // wrong order
}
}
return true;
}
/** Uses selection sort on an ArrayList
* 1. Originally the ArrayList is unsorted
* 2. We
select
the smallest number and swap it with the first element
* 3. Now the sorted subarray is the first item and the rest of the array is unsorted
* 4.
Select
the smallest of the unsorted numbers (the second smallest overall) and
* swap it with the second element
* 5. Now the first two elements are sorted and the rest are unsorted
* 6. Repeat until the rest of the elements are sorted
*/
public static ArrayList<Integer> selectionSort(ArrayList<Integer> array) {
for (int i = 0; i < array.size() - 1; i++) { // traverse to the second to last item, the last item is automatically the largest
int smallestIndex = i;
int smallestElement = array.get(i);
for (int j = i + 1; j < array.size(); j++) {
//traverse through the rest of the array, looking for the smallest remaining item (less than smallestElement)
if (array.get(j) < smallestElement) {
smallestIndex = j;
smallestElement = array.get(j);
}
}
if (smallestIndex > i) { // swap the elements of i and j if the element of i isn't already the smallest
int originalItem = array.get(i);
array.set(i, smallestElement);
array.set(smallestIndex, originalItem);
}
}
return array;
}
/** Uses insertion sort on an ArrayList
* 1. Assume the first element is already sorted
* 2. Select the second element
* 3.
Insert
it before the first element or keep it in place to make the first 2 elements sorted
* 4. Select the third element and
insert
it so that the first 3 elements are sorted
* 5. Repeat until all elements are sorted.
*/
public static ArrayList<Integer> insertionSort(ArrayList<Integer> array) {
for (int i = 1; i < array.size(); i++) {
int currentElement = array.get(i);
int currentIndex = i;
for (int j = i; j > 0; j--) {
if (currentElement < array.get(j - 1)) { // shifting the item left until properly placed by swapping consecutive items
int itemToRight = array.get(j - 1);
array.set(j - 1, currentElement);
array.set(j, itemToRight);
}
}
}
return array;
}
Β© 2023 Fiveable Inc. All rights reserved.