Unit 10
Unit 10
Recursion is when a method calls itself repeatedly to solve a problem Contain two parts
base case: condition to be reached or returned when conditions are met recursive call: the method being run over and over again uses if and else statement mainly
Binary seach algorithm: Data has to be in sorted order Splits array in half multiple times until value is found
Selection Sort: finds minimum element from unsorted part and puts it at end of sorted part
Merge Sort: splits array into 2, calls it self into two sorted halves, and then merges all the havles back into arrayList
public class Test {
public static void main(String[] args) {
String[][] arr = {
{ "a", "f", "g" },
{ "b", "e", "h" },
{ "c", "d", "i" }
};
// Print the last element in the array!
}
}
Test.main(null);
You can use Nested Loops to traverse 2D Arrays for example: to print out an entire array in order, you need to use these
Make sure your columns for loop is always inside your rows for loop! Unless you want it printed the other way of course Print spaces and lines in between to make a neater matrix
public class Test {
public static void main(String[] args) {
String[][] arr = {
{ "a", "f", "g", "l" },
{ "b", "e", "h", "k" },
{ "c", "d", "i", "j" }
};
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 4; col++) {
System.out.print(arr[row][col] + " ");
}
System.out.println(" ");
}
}
}
Test.main(null);
// Unit 10 recursion example
public int fact(int n) // a random number inputed, factorial of which wil be calculated
{
if (n == 1) // base case
return 1; //once n is found to be the same value as 1, the code stops
else
return n*fact(n-1); //if values not equal, then the function keeps calling the else part
}