This commit is contained in:
2024-01-26 15:30:51 -06:00
parent aef4bcc29c
commit 7962e14215
5 changed files with 262 additions and 0 deletions

14
MergeSort/pom.xml Normal file
View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.calebfontenot</groupId>
<artifactId>MergeSort</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>20</maven.compiler.source>
<maven.compiler.target>20</maven.compiler.target>
<exec.mainClass>com.calebfontenot.mergesort.MergeSort</exec.mainClass>
</properties>
</project>

View File

@@ -0,0 +1,88 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
*/
package com.calebfontenot.mergesort;
/**
*
* @author caleb
*/
public class MergeSort {
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
public static void main(String args[]) {
// merge sort = recursively divide array in 2, sort, re-combine
// run-time complexity = O(n Log n)
// space complexity = O(n)
int[] array = {8, 2, 5, 3, 4, 7, 6, 1, 0};
printArray(array);
mergeSort(array);
printArray(array);
}
private static void mergeSort(int[] array) {
int length = array.length;
if (length <= 1) {
return; //base case
}
int middle = length / 2;
int[] leftArray = new int[middle];
int[] rightArray = new int[length - middle];
int i = 0; //left array
int j = 0; //right array
for (; i < length; i++) {
if (i < middle) {
leftArray[i] = array[i];
} else {
rightArray[j] = array[i];
j++;
}
}
mergeSort(leftArray);
mergeSort(rightArray);
merge(leftArray, rightArray, array);
}
private static void merge(int[] leftArray, int[] rightArray, int[] array) {
int leftSize = array.length / 2;
int rightSize = array.length - leftSize;
int i = 0, l = 0, r = 0; //indices
//check the conditions for merging
while (l < leftSize && r < rightSize) {
if (leftArray[l] < rightArray[r]) {
array[i] = leftArray[l];
i++;
l++;
} else {
array[i] = rightArray[r];
i++;
r++;
}
}
while (l < leftSize) {
array[i] = leftArray[l];
i++;
l++;
}
while (r < rightSize) {
array[i] = rightArray[r];
i++;
r++;
}
}
}