Skip to content

Commit 8be79f5

Browse files
author
gzeiniss
committed
big o notation examples
0 parents  commit 8be79f5

9 files changed

+314
-0
lines changed

pom.xml

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xmlns="http://maven.apache.org/POM/4.0.0"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>com.genezeiniss</groupId>
8+
<artifactId>algorithm-complexity</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<properties>
12+
<maven.compiler.source>11</maven.compiler.source>
13+
<maven.compiler.target>11</maven.compiler.target>
14+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15+
</properties>
16+
</project>
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.genezeiniss;
2+
3+
public class Main {
4+
public static void main(String[] args) {
5+
System.out.println("Hello world!");
6+
}
7+
8+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.genezeiniss.big_o_notation;
2+
3+
import java.util.List;
4+
5+
// O(1): Constant Time Algorithm
6+
public class ConstantTimeExample {
7+
8+
// Accessing an element at a specific index in an array is an O(1) operation
9+
// because it takes the same amount of time regardless of the array size.
10+
public void accessElement(List<Integer> elements, int index) {
11+
int element = elements.get(index);
12+
System.out.printf("Element at index %s: %s", index, element);
13+
}
14+
15+
// Updating or assigning value to an array element at a specific index is also an O(1) operation because it takes constant time.
16+
public void updateElement(List<Integer> elements, int index) {
17+
elements.set(index, 100);
18+
System.out.printf("Updated element at index %s", index);
19+
}
20+
21+
// Checking the length of an array is an O(1) operation because it's simply accessing a property of the array.
22+
public void checkLength(List<Integer> elements) {
23+
int length = elements.size();
24+
System.out.printf("Length of elements list is %s", length);
25+
}
26+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.genezeiniss.big_o_notation;
2+
3+
import java.util.stream.IntStream;
4+
5+
// O(2^n): Exponential Time Complexity
6+
public class ExponentialTimeComplexity {
7+
8+
public static void main(String[] args) {
9+
// Example: Calculate and print the first 10 Fibonacci numbers
10+
int n = 10;
11+
System.out.printf("Fibonacci sequence up to %s terms: ", n);
12+
13+
IntStream.range(0, n)
14+
.mapToObj(i -> fibonacci(i) + " ")
15+
.forEach(System.out::print);
16+
}
17+
18+
public static int fibonacci(int n) {
19+
return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2);
20+
}
21+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.genezeiniss.big_o_notation;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
// O(n!): Factorial Time Complexity
7+
public class FactorialTimeComplexity {
8+
9+
public static void main(String[] args) {
10+
List<Integer> nums = List.of(1, 2, 3);
11+
List<List<Integer>> permutations = permute(new ArrayList<>(nums));
12+
System.out.printf("Permutations of %s:\n", nums);
13+
permutations.forEach(System.out::println);
14+
}
15+
16+
// Method to generate all permutations of a list
17+
public static List<List<Integer>> permute(List<Integer> nums) {
18+
List<List<Integer>> result = new ArrayList<>();
19+
permuteHelper(nums, 0, result);
20+
return result;
21+
}
22+
23+
// Helper method to generate permutations recursively
24+
private static void permuteHelper(List<Integer> nums, int start, List<List<Integer>> result) {
25+
if (start == nums.size() - 1) {
26+
result.add(new ArrayList<>(nums));
27+
return;
28+
}
29+
for (int i = start; i < nums.size(); i++) {
30+
swap(nums, i, start);
31+
permuteHelper(nums, start + 1, result);
32+
swap(nums, i, start); // backtrack
33+
}
34+
}
35+
36+
// Method to swap elements in a list
37+
private static void swap(List<Integer> nums, int i, int j) {
38+
int temp = nums.get(i);
39+
nums.set(i, nums.get(j));
40+
nums.set(j, temp);
41+
}
42+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.genezeiniss.big_o_notation;
2+
3+
import java.util.List;
4+
import java.util.stream.Collectors;
5+
import java.util.stream.IntStream;
6+
7+
// O(n): Linear Time Complexity
8+
public class LinearTimeExample {
9+
10+
public static void main(String[] args) {
11+
// Simulating a book with 1000 pages
12+
List<String> book = IntStream.range(0, 1000)
13+
.mapToObj(LinearTimeExample::toChineseNumber)
14+
.collect(Collectors.toList());
15+
16+
// The page we want to find (e.g., page 512 in Chinese characters)
17+
String targetPage = toChineseNumber(512);
18+
19+
// Performing the linear search
20+
int checks = linearSearch(book, targetPage);
21+
System.out.printf("Number of checks needed: %s\n", checks);
22+
}
23+
24+
public static int linearSearch(List<String> book, String targetPage) {
25+
int checks = 0;
26+
27+
for (String page : book) {
28+
checks++;
29+
if (page.equals(targetPage)) {
30+
return checks;
31+
}
32+
}
33+
34+
return -1; // Page not found
35+
}
36+
37+
private static String toChineseNumber(int number) {
38+
List<String> units = List.of("", "十", "百", "千", "万"); // This list contains Chinese characters for units like ten, hundred, thousand, and ten thousand.
39+
List<String> digits = List.of("零", "一", "二", "三", "四", "五", "六", "七", "八", "九"); // This array contains Chinese characters for the digits 0 through 9.
40+
41+
// If the input number is zero, the function directly returns "零", which is the Chinese character for zero.
42+
if (number == 0) {
43+
return digits.get(0);
44+
}
45+
46+
StringBuilder chineseNumber = new StringBuilder();
47+
int unitIndex = 0;
48+
49+
// The function uses a loop to process each digit of the input number from right to left.
50+
while (number > 0) {
51+
int digit = number % 10; // Extracts the rightmost digit of the number.
52+
if (digit != 0) { // If the digit is not zero, it prepends the corresponding Chinese digit and unit to the StringBuilder.
53+
chineseNumber.insert(0, digits.get(digit) + units.get(unitIndex));
54+
} else if (chineseNumber.length() > 0 && chineseNumber.charAt(0) != '零') { // If the digit is zero and the current Chinese number being built doesn't already start with zero, it prepends "零".
55+
chineseNumber.insert(0, digits.get(digit));
56+
}
57+
number /= 10; // Removes the rightmost digit from the number
58+
unitIndex++; // Moves to the next unit (ten, hundred, thousand, etc.)
59+
}
60+
61+
return chineseNumber.toString();
62+
}
63+
}
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
package com.genezeiniss.big_o_notation;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
// O(n log n): Linearithmic Time Complexity
8+
public class LinearithmicTimeComplexity {
9+
10+
public static void main(String[] args) {
11+
List<Integer> list = Arrays.asList(38, 27, 43, 3, 9, 82, 10);
12+
System.out.printf("Original list: %s\n", list);
13+
14+
List<Integer> sortedList = mergeSort(list);
15+
System.out.printf("Sorted list: %s\n", sortedList);
16+
}
17+
18+
public static List<Integer> mergeSort(List<Integer> list) {
19+
// Base case: a list with zero or one element is already sorted
20+
if (list.size() <= 1) {
21+
return list;
22+
}
23+
24+
// Divide: The dataset is repeatedly divided in half until each sub-array contains a single element.
25+
// The number of times you can divide n elements in half is log(n).
26+
int middle = list.size() / 2;
27+
List<Integer> left = list.subList(0, middle);
28+
List<Integer> right = list.subList(middle, list.size());
29+
30+
// Conquer: Each of these single-element arrays is trivially sorted.
31+
left = mergeSort(left);
32+
right = mergeSort(right);
33+
34+
// Combine: The sorted sub-arrays are merged back together.
35+
// Merging n elements requires linear time, O(n).
36+
return merge(left, right);
37+
}
38+
39+
public static List<Integer> merge(List<Integer> left, List<Integer> right) {
40+
List<Integer> result = new ArrayList<>();
41+
int leftIndex = 0, rightIndex = 0;
42+
43+
// Merge the two lists while there are elements in both
44+
while (leftIndex < left.size() && rightIndex < right.size()) {
45+
if (left.get(leftIndex) <= right.get(rightIndex)) {
46+
result.add(left.get(leftIndex++));
47+
} else {
48+
result.add(right.get(rightIndex++));
49+
}
50+
}
51+
52+
// If there are remaining elements in the left list, add them
53+
while (leftIndex < left.size()) {
54+
result.add(left.get(leftIndex++));
55+
}
56+
57+
// If there are remaining elements in the right list, add them
58+
while (rightIndex < right.size()) {
59+
result.add(right.get(rightIndex++));
60+
}
61+
62+
return result;
63+
}
64+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.genezeiniss.big_o_notation;
2+
3+
// O(log n): Logarithmic Time Complexity
4+
public class LogarithmicTimeExample {
5+
6+
public static void main(String[] args) {
7+
var totalPages = 1000;
8+
var targetPage = 512;
9+
10+
var checks = binarySearch(totalPages, targetPage);
11+
System.out.printf("Number of checks needed: %s\n", checks);
12+
}
13+
14+
public static int binarySearch(int totalPages, int targetPage) {
15+
int low = 1;
16+
int high = totalPages;
17+
int checks = 0;
18+
19+
while (low <= high) {
20+
int mid = low + (high - low) / 2;
21+
checks++; // Counting the number of checks
22+
23+
switch (Integer.compare(mid, targetPage)) {
24+
case 0:
25+
return checks;
26+
case -1:
27+
low = mid + 1;
28+
break;
29+
case 1:
30+
high = mid - 1;
31+
break;
32+
}
33+
}
34+
35+
return -1; // Page not found
36+
}
37+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.genezeiniss.big_o_notation;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
6+
// O(n^2): Quadratic Time Complexity
7+
public class QuadraticTimeComplexity {
8+
9+
public static void main(String[] args) {
10+
List<Integer> list = Arrays.asList(64, 34, 25, 12, 22, 11, 90);
11+
System.out.printf("Unsorted list: %s\n", list);
12+
13+
bubbleSort(list);
14+
System.out.printf("Sorted list: %s\n", list);
15+
}
16+
17+
public static void bubbleSort(List<Integer> list) {
18+
int n = list.size();
19+
boolean swapped;
20+
21+
for (int i = 0; i < n - 1; i++) {
22+
swapped = false;
23+
// Inner loop to perform the comparisons and swaps
24+
for (int j = 0; j < n - i - 1; j++) {
25+
// If the current element is greater than the next element, swap them
26+
if (list.get(j) > list.get(j + 1)) {
27+
int temp = list.get(j);
28+
list.set(j, list.get(j + 1));
29+
list.set(j + 1, temp);
30+
swapped = true;
31+
}
32+
}
33+
// If no elements were swapped during the inner loop, the array is sorted
34+
if (!swapped) break;
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)