Skip to content

Commit dad523d

Browse files
Merge pull request #7 from CamJSP-Community/sorts
Sorts
2 parents 97d3a83 + 003fc21 commit dad523d

17 files changed

+1031
-0
lines changed

sorts/.gitignore

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
target/
2+
!.mvn/wrapper/maven-wrapper.jar
3+
!**/src/main/**/target/
4+
!**/src/test/**/target/
5+
6+
### IntelliJ IDEA ###
7+
.idea/
8+
*.iws
9+
*.iml
10+
*.ipr
11+
12+
### Eclipse ###
13+
.apt_generated
14+
.classpath
15+
.factorypath
16+
.project
17+
.settings
18+
.springBeans
19+
.sts4-cache
20+
21+
### NetBeans ###
22+
/nbproject/private/
23+
/nbbuild/
24+
/dist/
25+
/nbdist/
26+
/.nb-gradle/
27+
build/
28+
!**/src/main/**/build/
29+
!**/src/test/**/build/
30+
31+
### VS Code ###
32+
.vscode/
33+
34+
### Mac OS ###
35+
.DS_Store

sorts/README.md

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
# Sorting Algorithms
2+
3+
This project demonstrates the implementation of multiple sorting algorithms. Sorting algorithms are essential in computer science for ordering data, making it easier to analyze, search, or optimize resources.
4+
5+
## Overview
6+
7+
Sorting algorithms take a collection of items (often numbers or strings) and arrange them in a specific order. In this project, each algorithm is implemented in a generic way to allow for sorting different types of data, provided that they implement the `Comparable` interface.
8+
9+
The key sorting algorithms included are:
10+
11+
- **Bubble Sort**
12+
- **Selection Sort**
13+
- **Insertion Sort**
14+
- **Merge Sort**
15+
- **Quick Sort**
16+
17+
Each algorithm is analyzed in terms of its:
18+
- **Time Complexity**: How fast it performs relative to the input size.
19+
- **Space Complexity**: The amount of additional memory it uses.
20+
- **Stability**: Whether it preserves the order of equal elements.
21+
22+
## Algorithms
23+
24+
### 1. Bubble Sort
25+
A simple, comparison-based algorithm that repeatedly steps through the list, compares adjacent items, and swaps them if they are out of order.
26+
27+
- **Time Complexity**: O(n^2) in the worst and average cases, O(n) in the best case when the array is already sorted.
28+
- **Space Complexity**: O(1)
29+
- **Stability**: Stable
30+
31+
### 2. Selection Sort
32+
Selects the minimum element from the unsorted portion of the list and swaps it with the first unsorted element.
33+
34+
- **Time Complexity**: O(n^2) for all cases.
35+
- **Space Complexity**: O(1)
36+
- **Stability**: Not stable (may require modifications for stability)
37+
38+
### 3. Insertion Sort
39+
Builds the final sorted list one element at a time by comparing each new element to the sorted elements and inserting it in the correct position.
40+
41+
- **Time Complexity**: O(n^2) in the worst and average cases, O(n) in the best case.
42+
- **Space Complexity**: O(1)
43+
- **Stability**: Stable
44+
45+
### 4. Merge Sort
46+
A divide-and-conquer algorithm that divides the list into halves, sorts each half, and then merges the two sorted halves together.
47+
48+
- **Time Complexity**: O(n log n) for all cases.
49+
- **Space Complexity**: O(n) due to the need for temporary arrays.
50+
- **Stability**: Stable
51+
52+
### 5. Quick Sort
53+
A highly efficient divide-and-conquer algorithm that selects a "pivot" element, partitions the list around the pivot, and then recursively sorts the partitions.
54+
55+
- **Time Complexity**: O(n log n) on average, O(n^2) in the worst case (can be optimized with random pivots).
56+
- **Space Complexity**: O(log n) on average due to recursion, O(n) in the worst case.
57+
- **Stability**: Not stable
58+
59+
## Running the Project
60+
61+
1. **Compile the Code**: Make sure you have Java and Maven installed, and then compile the code using Maven with the following command:
62+
63+
```bash
64+
mvn compile
65+
```
66+
67+
2. **Run the Sorting Algorithms**: To run the main program, use Maven with the following command:
68+
69+
```bash
70+
mvn exec:java -Dexec.mainClass="com.brandoniscoding.Main"
71+
```
72+
73+
3. **Run the Tests**: To execute the unit tests for the sorting algorithms, run the following Maven command:
74+
75+
```bash
76+
mvn test
77+
```
78+
79+
This will execute all the tests defined in the project and show the results in the terminal.
80+
81+
82+
## Contributing
83+
84+
1. **Fork the Repository**: Make your changes in a branch from `master`.
85+
2. **Commit Messages**: Follow conventions, e.g., `feat: add new sorting algorithm` or `fix: optimize quicksort partition`.
86+
3. **Pull Requests**: Ensure your code passes all tests before opening a pull request.
87+
88+
## License
89+
90+
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

sorts/pom.xml

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.brandoniscoding</groupId>
8+
<artifactId>sorts</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<properties>
12+
<maven.compiler.source>22</maven.compiler.source>
13+
<maven.compiler.target>22</maven.compiler.target>
14+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
15+
</properties>
16+
17+
<dependencies>
18+
<dependency>
19+
<groupId>org.junit.jupiter</groupId>
20+
<artifactId>junit-jupiter-api</artifactId>
21+
<version>5.11.2</version>
22+
<scope>test</scope>
23+
</dependency>
24+
25+
<dependency>
26+
<groupId>org.junit.jupiter</groupId>
27+
<artifactId>junit-jupiter-engine</artifactId>
28+
<version>5.11.2</version>
29+
<scope>test</scope>
30+
</dependency>
31+
</dependencies>
32+
33+
<build>
34+
<plugins>
35+
<plugin>
36+
<groupId>org.apache.maven.plugins</groupId>
37+
<artifactId>maven-surefire-plugin</artifactId>
38+
<version>3.5.1</version>
39+
</plugin>
40+
41+
</plugins>
42+
</build>
43+
44+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package com.brandoniscoding;
2+
3+
import java.util.Scanner;
4+
import com.brandoniscoding.algorithms.BubbleSort;
5+
import com.brandoniscoding.algorithms.InsertionSort;
6+
import com.brandoniscoding.algorithms.MergeSort;
7+
import com.brandoniscoding.algorithms.QuickSort;
8+
import com.brandoniscoding.algorithms.SortAlgorithm;
9+
import com.brandoniscoding.utils.MainUtils;
10+
11+
public class Main {
12+
public static void main(String[] args) {
13+
Scanner scanner = new Scanner(System.in);
14+
15+
// Displaying a welcome message
16+
System.out.println("=== Sorting Algorithm Test ===");
17+
System.out.println("Choose the sorting algorithm and the action to perform.\n");
18+
19+
// Getting input array from the user
20+
Integer[] dataArray = MainUtils.inputData(scanner);
21+
22+
// Main loop for selecting sorting algorithm and actions
23+
while (true) {
24+
MainUtils.displayAlgorithmMenu();
25+
int algorithmChoice = MainUtils.getUserChoice(scanner);
26+
27+
SortAlgorithm<Integer> selectedAlgorithm = null;
28+
switch (algorithmChoice) {
29+
case 1:
30+
selectedAlgorithm = new BubbleSort<>();
31+
break;
32+
case 2:
33+
selectedAlgorithm = new InsertionSort<>();
34+
break;
35+
case 3:
36+
selectedAlgorithm = new MergeSort<>();
37+
break;
38+
case 4:
39+
selectedAlgorithm = new QuickSort<>();
40+
break;
41+
case 0:
42+
System.out.println("Exiting program. Goodbye!");
43+
return;
44+
default:
45+
System.out.println("Invalid choice. Please try again.");
46+
continue;
47+
}
48+
49+
// Action menu: execute sort or display description
50+
System.out.println("1. Execute the sort");
51+
System.out.println("2. Display the algorithm description");
52+
System.out.print("Enter your choice: ");
53+
int actionChoice = MainUtils.getUserChoice(scanner);
54+
55+
if (actionChoice == 1) {
56+
System.out.println("\n--- Before Sorting ---");
57+
MainUtils.printArray(dataArray);
58+
59+
// Measure and execute sort
60+
long startTime = System.nanoTime();
61+
selectedAlgorithm.sort(dataArray);
62+
long endTime = System.nanoTime();
63+
64+
System.out.println("\n--- After Sorting ---");
65+
MainUtils.printArray(dataArray);
66+
67+
// Display execution time
68+
long duration = endTime - startTime;
69+
System.out.println("\nExecution Time: " + duration + " nanoseconds.");
70+
} else if (actionChoice == 2) {
71+
System.out.println("\nAlgorithm Description:");
72+
System.out.println(selectedAlgorithm.getDescription());
73+
} else {
74+
System.out.println("Invalid option. Please try again.");
75+
}
76+
}
77+
}
78+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.brandoniscoding.algorithms;
2+
3+
import static com.brandoniscoding.utils.ArrayUtils.swap;
4+
5+
public class BubbleSort<T extends Comparable<T>> implements SortAlgorithm<T> {
6+
7+
public BubbleSort() {}
8+
9+
@Override
10+
public void sort(T[] array) {
11+
int n = array.length;
12+
for (int i = 0; i < n - 1; i++) {
13+
for (int j = 0; j < n - i - 1; j++) {
14+
if (array[j].compareTo(array[j + 1]) > 0) { // Compare elements and swap if needed
15+
swap(array, j, j + 1); // Swap elements
16+
}
17+
}
18+
}
19+
}
20+
21+
@Override
22+
public String getDescription() {
23+
return "Bubble Sort Algorithm: A comparison-based sorting algorithm.\n\n" +
24+
"Algorithm Steps:\n" +
25+
"1. **Start at the first element**: Begin at the first element of the array.\n" +
26+
"2. **Compare adjacent elements**: Compare the current element with the next one.\n" +
27+
"3. **Swap if needed**: If the current element is greater than the next, swap them.\n" +
28+
"4. **Move to the next element**: Move to the next element and repeat the comparison and swap process until the end of the array.\n" +
29+
"5. **Bubble the largest element**: After each pass through the array, the largest unsorted element is 'bubbled' to its correct position.\n" +
30+
"6. **Repeat the process**: Repeat steps 1-5 for the remaining unsorted portion of the array.\n" +
31+
"7. **Stop when no swaps are needed**: The algorithm finishes when no more swaps are made, meaning the array is sorted.\n\n" +
32+
"Time Complexity:\n" +
33+
" - Worst case: O(n^2), when the array is in reverse order and each element must be swapped during every pass.\n" +
34+
" - Best case: O(n), when the array is already sorted (optimized version where we track if swaps occurred).\n" +
35+
" - Average case: O(n^2), for random inputs, as each pass through the array requires comparing and potentially swapping adjacent elements.\n\n" +
36+
"Space Complexity:\n" +
37+
" - O(1), as the algorithm is performed in-place, requiring no additional memory beyond a constant amount for temporary variables.";
38+
}
39+
40+
41+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.brandoniscoding.algorithms;
2+
3+
public class InsertionSort<T extends Comparable<T>> implements SortAlgorithm<T> {
4+
5+
public InsertionSort() {}
6+
7+
@Override
8+
public void sort(T[] array) {
9+
for (int i = 1; i < array.length; i++) {
10+
T current = array[i]; // Current element to be inserted
11+
int j = i - 1;
12+
13+
// Compare current element with the sorted part of the array
14+
while (j >= 0 && array[j].compareTo(current) > 0) {
15+
array[j + 1] = array[j]; // Shift elements to the right
16+
j = j - 1;
17+
}
18+
19+
array[j + 1] = current; // Insert the current element at its correct position
20+
}
21+
}
22+
23+
@Override
24+
public String getDescription() {
25+
return "Insertion Sort Algorithm: A comparison-based sorting algorithm.\n\n" +
26+
"Algorithm Steps:\n" +
27+
"1. **Start with the second element**: Begin traversing the array from the second element (index 1) because the first element is trivially sorted.\n" +
28+
"2. **Compare with the sorted portion**: At each iteration, compare the current element with the previous elements in the already sorted part of the array.\n" +
29+
"3. **Find the correct position**: If the current element is smaller than the compared element, shift the larger elements one position to the right to make space.\n" +
30+
"4. **Insert the current element**: Place the current element at its correct position in the sorted part.\n" +
31+
"5. **Repeat for the next elements**: Move to the next element and repeat the process until the entire array is sorted.\n\n" +
32+
"Time Complexity:\n" +
33+
" - Worst case: O(n^2), when the array is in reverse order and each insertion requires shifting all previous elements.\n" +
34+
" - Best case: O(n), when the array is already nearly sorted (only small shifts are required).\n" +
35+
" - Average case: O(n^2), for random inputs, as each insertion may require shifting multiple elements.\n\n" +
36+
"Space Complexity:\n" +
37+
" - O(1), as the algorithm is performed in-place, requiring no extra space beyond a constant amount for temporary variables like the current element.";
38+
}
39+
40+
41+
}

0 commit comments

Comments
 (0)