add examples in java 8 (#12)
* code for chapters 3-9 in Java * code for chapters 1 in Java * code for chapter 2 in Java * missing CheckVoter for chapter 5 in Java * add missing sample output for SetCovering as a comment
This commit is contained in:
committed by
Aditya Bhargava
parent
12265a8c61
commit
4631b7a156
37
02_selection_sort/java/src/SelectionSort.java
Normal file
37
02_selection_sort/java/src/SelectionSort.java
Normal file
@@ -0,0 +1,37 @@
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class SelectionSort {
|
||||
|
||||
private static List<Integer> selectionSort(List<Integer> arr) {
|
||||
List<Integer> newArr = new ArrayList<>(arr.size());
|
||||
|
||||
int size = arr.size();
|
||||
for (int i = 0; i < size; i++) {
|
||||
int smallest = findSmallest(arr);
|
||||
newArr.add(arr.get(smallest));
|
||||
|
||||
arr.remove(smallest);
|
||||
}
|
||||
|
||||
return newArr;
|
||||
}
|
||||
|
||||
private static int findSmallest(List<Integer> arr) {
|
||||
int smallest = arr.get(0);
|
||||
int smallestIndex = 0;
|
||||
for (int i = 0; i < arr.size(); i++) {
|
||||
if (arr.get(i) < smallest) {
|
||||
smallest = arr.get(i);
|
||||
smallestIndex = i;
|
||||
}
|
||||
}
|
||||
return smallestIndex;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
List<Integer> arr = new ArrayList<>(Arrays.asList(5, 3, 6, 2, 10));
|
||||
System.out.println(selectionSort(arr)); //[2, 3, 5, 6, 10]
|
||||
}
|
||||
}
|
||||
33
02_selection_sort/java/src/SelectionSort2.java
Normal file
33
02_selection_sort/java/src/SelectionSort2.java
Normal file
@@ -0,0 +1,33 @@
|
||||
import java.util.Arrays;
|
||||
|
||||
public class SelectionSort2 {
|
||||
|
||||
// this version uses raw arrays instead of ArrayList
|
||||
private static int[] selectionSort(int[] arr) {
|
||||
int[] newArr = new int[]{arr.length};
|
||||
|
||||
for (int i = 0; i < newArr.length; i++) {
|
||||
int smallest = findSmallest(arr, i);
|
||||
newArr[i] = arr[smallest];
|
||||
}
|
||||
|
||||
return newArr;
|
||||
}
|
||||
|
||||
private static int findSmallest(int[] arr, int low) {
|
||||
int smallest = arr[low];
|
||||
int smallestIndex = low;
|
||||
for (int i = low + 1; i < arr.length; i++) {
|
||||
if (arr[i] < smallest) {
|
||||
smallest = arr[i];
|
||||
smallestIndex = i;
|
||||
}
|
||||
}
|
||||
return smallestIndex;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
int[] arr = {5, 3, 6, 2, 10};
|
||||
System.out.println(Arrays.toString(selectionSort(arr))); // [2, 3, 5, 6, 10]
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user