Compare commits

...

7 Commits

Author SHA1 Message Date
96ce281b20 Mod 7 quicksort 2025-03-09 17:58:29 +05:30
67a7b0e096 Mod 6 mergesort 2025-03-09 15:28:04 +05:30
9e9d30accf Mod 5 all sorts 2025-03-08 22:26:57 +05:30
f12dd3574e Mod 5 all sorts 2025-03-08 22:19:02 +05:30
0f662bf89c Adding heap sort to practice 2025-02-16 21:59:28 +00:00
2679715bb2 Heapsort Implementation 2025-02-16 21:59:28 +00:00
b8f6081173 practice (#13)
Reviewed-on: Hithomelabs/Princeton1#13
Co-authored-by: hitanshu310 <hitanshu98@gmail.com>
Co-committed-by: hitanshu310 <hitanshu98@gmail.com>
2025-02-07 21:00:19 +00:00
21 changed files with 364 additions and 364 deletions

3
.gitignore vendored
View File

@ -1,6 +1,7 @@
# Ignore Gradle project-specific cache directory
.gradle
# Igonre the .idea directory
.idea
# Ignore Gradle build output directory
build
bin

1
.idea/gradle.xml generated
View File

@ -14,6 +14,7 @@
<option value="$PROJECT_DIR$/module5" />
<option value="$PROJECT_DIR$/module6" />
<option value="$PROJECT_DIR$/module7" />
<option value="$PROJECT_DIR$/module8" />
</set>
</option>
</GradleProjectSettings>

View File

@ -16,6 +16,7 @@ dependencies {
implementation project(':module5')
implementation project(':module6')
implementation project(':module7')
implementation project(':module8')
implementation project(':common')
testImplementation project(':common')
}

View File

@ -0,0 +1,23 @@
package com.hithomelabs.clients.module8;
import com.hithomelabs.princeton1.common.Apple;
import com.hithomelabs.princeton1.module8.HeapSort;
import java.util.Random;
public class HeapSortClient {
public static void main(String[] args) {
int size = 10;
Apple[] apples = new Apple[size];
HeapSort<Apple> heap = new HeapSort<Apple>();
for (int i = 0; i < apples.length; i++) {
apples[i] = new Apple(new Random().nextInt(10));
}
heap.sort(apples);
for (int i = 0; i < apples.length; i++)
System.out.println(apples[i]);
}
}

View File

@ -5,100 +5,28 @@ import java.util.Iterator;
import javax.annotation.Nonnull;
public class ArrayQueue<E> extends Queue<E>{
// insertion from tail, removal from head
public static final int DEFAULT_CAPACITY = 10;
private int capacity;
private int tail;
private int head;
private int size;
private E[] arr;
public ArrayQueue(){
this(DEFAULT_CAPACITY);
}
public ArrayQueue(int capacity){
this.capacity = capacity;
arr = (E[]) new Object[this.capacity];
size = 0;
}
@Override
public boolean isEmpty() {
return size == 0;
return false;
}
@Override
public E dequeue() {
if(isEmpty())
return null;
else{
E element = arr[head];
// Garbage collection
arr[head] = null;
head = (head+1)%capacity;
size = size - 1;
if(capacity >= 40 && size < capacity/4){
capacity = capacity/2;
resize(capacity, capacity*2);
}
return element;
}
return null;
}
@Override
public void enqueue(E element) {
// We plan capacity expansion if needed
if (size == capacity){
capacity = capacity * 2;
resize(capacity, capacity/2);
}
arr[tail] = element;
tail = (tail + 1) % capacity;
++size;
}
// When resize takes place always the original array is full, so copy the complete array as is
private void resize(int capacity, int oldCapacity) {
E[] resizedArr = (E[]) new Object[capacity];
for(int i = 0; i < size; i++) {
resizedArr[i] = arr[head];
// halving because capacity has now doubled
arr[head] = null;
head = (head + 1) % oldCapacity;
}
arr = resizedArr;
// When resizing takes place, we bring the head to 0 and the tail to size
// tail is where new inserts will be made and head will be where elements will be removed
tail = size;
head = 0;
}
@Override
public int size() {
return size;
return 0;
}
@Override
@Nonnull
public Iterator<E> iterator() {
return new Iterator<E>() {
int counter = size;
int pointer = head;
@Override
public boolean hasNext() {
return counter != 0;
}
@Override
public E next() {
E element = arr[pointer];
pointer = (pointer + 1)% capacity;
--counter;
return element;
}
};
return null;
}
}

View File

@ -5,94 +5,28 @@ import javax.annotation.Nonnull;
// Concrete implementation of stack using arrays
// Creating a generic stack of type E
public class ArrayStack<E> extends Stack<E> {
// Capacity and size are two variables, capacity determines total capacity of array, capacity defaults at 10
// every time size == capacity, capacity = 2 * capacity
private static final int DEFAULT_CAPACITY = 10;
private int capacity;
private int size;
private E[] arr;
public ArrayStack(int capacity){
this.capacity = capacity;
arr = (E[]) new Object[this.capacity];
}
// Constructor chaining, default constructor will call parametrized constructor with default initial capacity 10
public ArrayStack(){
this(DEFAULT_CAPACITY);
}
@Override
public boolean isEmpty() {
return size == 0;
return false;
}
private void changeCapacity(int newCapacity){
E[] resizedArr = (E[]) new Object[newCapacity];
for (int i = 0; i < size; i++)
resizedArr[i] = arr[i];
arr = resizedArr;
}
private void incrementSize(){
if (size == capacity){
capacity = 2 * capacity;
changeCapacity(capacity);
}
}
// Push always happens at the end of the stack
// Say the size of the stack is 1, new element gets inserted at 1
@Override
public void push(E element) {
// Lazy approach, we assume size to always be lesser than capacity
incrementSize();
arr[size++] = element;
}
@Override
public E pop() {
if (isEmpty())
return null;
else{
E e = arr[--size];
arr[size] = null;
checkResize();
return e;
}
}
private void checkResize() {
if (size < capacity / 4 && capacity >= 20){
capacity = capacity / 2;
changeCapacity(capacity);
}
return null;
}
@Override
public int size() {
return size;
return 0;
}
@Override
@Nonnull
public Iterator<E> iterator() {
return new Iterator<E>() {
int current = 0;
@Override
public boolean hasNext() {
return current != size;
}
@Override
public E next() {
E element = arr[current];
current = current + 1;
return element;
}
};
return null;
}
}

View File

@ -4,71 +4,28 @@ import javax.annotation.Nonnull;
import java.util.Iterator;
public class LinkedQueue<E> extends Queue<E>{
Node head;
Node tail;
int size;
private class Node{
E value;
Node next;
Node(E value){
this.value = value;
}
}
@Override
public boolean isEmpty() {
return size==0;
return false;
}
@Override
public E dequeue() {
if(isEmpty())
return null;
E element = head.value;
// Only a single element is present
if (head == tail){
tail = null;
}
head = head.next;
--size;
return element;
return null;
}
@Override
public void enqueue(E element) {
Node newNode = new Node(element);
if(isEmpty())
head = newNode;
else
tail.next = newNode;
tail = newNode;
++size;
}
@Override
public int size() {
return size;
return 0;
}
@Override
@Nonnull
public Iterator<E> iterator() {
return new Iterator<E>() {
Node current = head;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public E next() {
E element = current.value;
current = current.next;
return element;
}
};
return null;
}
}

View File

@ -3,70 +3,28 @@ import java.util.Iterator;
// Creating a concrete linked Implementation of Stack
public class LinkedStack<E> extends Stack<E>{
// No need for an explicit constructor as size will be initialized to 0 and root to null
private int size;
private Node first;
// By default instance variables are package private
private class Node{
E value;
Node next;
}
// Will return true if size is 0
@Override
public boolean isEmpty() {
return (this.size == 0);
return false;
}
// Adds an element to the start of a linked list
@Override
public void push(E element) {
Node newNode = new Node();
newNode.value = element;
newNode.next = first;
first = newNode;
this.size = this.size + 1;
}
@Override
public E pop() {
if (this.isEmpty())
return null;
else{
Node toBePopped = first;
first = first.next;
this.size = this.size - 1;
return toBePopped.value;
}
return null;
}
@Override
public int size() {
return this.size;
return 0;
}
@Override
public Iterator<E> iterator() {
return new Iterator<E>() {
// Internal classes can access outer objects
Node current = first;
@Override
public boolean hasNext() {
return current != null;
}
@Override
public E next() {
E element = current.value;
current = current.next;
return element;
}
};
return null;
}
}

View File

@ -4,12 +4,14 @@ public abstract class AbstractCustomSorts<E> {
public abstract void sort(E[] arr);
// TODO: Implement this method
public void exch(E[] arr, int j, int i) {
E temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
E temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
// TODO: Implement this method
public boolean less(Comparable<E> e1, E e2) {
return e1.compareTo(e2) < 0;
}

View File

@ -1,23 +1,31 @@
package com.hithomelabs.princeton1.module5;
public class Insertion<E> extends AbstractCustomSorts<E> {
@Override
public void sort(E[] arr) {
int N = arr.length;
public void sort(E[] arr){
if (arr == null) return;
else{
int N = arr.length;
// * * swap arr[i] with each element greater to it's left
for (int i = 1; i < N; i++){
int j = i;
while(j >= 1 && less((Comparable<E>)arr[j], arr[j-1])){
for(int i=0; i<N; i++){
for(int j=i; j>0; j--){
if(less( (Comparable<E>) arr[j], arr[j-1]))
exch(arr, j, j-1);
j = j-1;
}
else
break;
}
}
}
public void sort(E[] arr, int h) {
int N = arr.length;
for(int i=0; i<N; i++){
for(int j=i; j>0; j=j-h){
if(less( (Comparable<E>) arr[j], arr[j-1]))
exch(arr, j, j-1);
else
break;
}
}
}
}

View File

@ -1,23 +1,22 @@
package com.hithomelabs.princeton1.module5;
/*
* * Selection sort "selects" the smallest element and swaps it with arr[0] of the array
* * Then proceeds to do the same swapping arr[i] with arr[i:arr.length-1]
*/
public class Selection<E> extends AbstractCustomSorts<E>{
@Override
public void sort(E[] arr) {
int N=arr.length;
/*
* * Selection sort "selects" the smallest element and swaps it with arr[0] of the array
* * Then proceeds to do the same swapping arr[i] with arr[i:arr.length-1]
*/
public void sort(E[] arr){
if (arr == null) return;
Comparable<E>[] arr1 = (Comparable<E>[]) arr;
for(int i = 0; i < arr1.length - 1; i++){
int minIndex = i;
for(int j = i+1; j < arr.length; j ++){
if (less((Comparable<E>) arr[j], arr[minIndex])) minIndex = j;
for(int i=0; i<N; i++){
int min=i;
for(int j=i+1; j<N; j++){
if(less((Comparable<E>) arr[j], arr[min]))
min=j;
}
exch(arr, i, minIndex);
exch(arr, min, i);
}
}
}

View File

@ -24,33 +24,21 @@ public class Shell<E> extends AbstractCustomSorts<E> {
*/
@Override
public void sort(E[] arr) {
MetaData metaData = new MetaData();
int N = arr.length;
int h = 1;
// * * Calculates the largest value of h greater than n
while (3 * h + 1 < N) {
h = 3 * h + 1;
Insertion<E> sortingAlgorithm = new Insertion<>();
int h=1, N=arr.length;
while(h < N/3)
h = 3*h + 1;
while( h >= 1){
sortingAlgorithm.sort(arr, h);
h=h/3;
}
while (h >= 1) {
h = hsort(arr, h, metaData);
h = h / 3;
}
System.out.println("Array sorted (shell sort) with " + metaData.compares + " compares and " + metaData.swaps + " swaps");
}
private int hsort(E[] arr, int h, MetaData metadata) {
int N = arr.length;
for(int i = h; i < N; i++){
int j = i;
++metadata.compares;
while(j >= h && less((Comparable<E>) arr[j], arr[j-h])){
++metadata.swaps;
exch(arr, j, j-h);
j = j - h;
++metadata.compares;
}
}
return h;
return 0;
}
/*
* Sample implementation of insertion sort as h-sort of h = 1

View File

@ -6,51 +6,91 @@ import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import com.hithomelabs.princeton1.common.Apple;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
class SortTest {
private ArrayList<Apple> apples;
private Apple[] apples, applesCopy;
private AbstractCustomSorts<Apple> sortingAlgorithm;
private Random random;
@BeforeEach
void setUp() {
apples = new ArrayList<Apple>();
apples = new Apple[100];
// applesCopy = new Apple[100];
//sortingAlgorithm = new Selection<Apple>();
random = new Random();
}
private void testSort(AbstractCustomSorts<Apple> sortingAlgorithm) {
for (int i = 0; i < 100; i++)
apples.add(new Apple(random.nextInt(100)));
private void testSort() {
int value;
for (int i = 0; i < 100; i++) {
value = random.nextInt(100);
apples[i] = new Apple(value);
// applesCopy[i] = new Apple(value);
}
}
private boolean test(){
for(int i=0;i<99;i++){
if(apples[i].compareTo(apples[i+1]) > 0)
return false;
}
return true;
}
@Test
@DisplayName("Testing Insertion sort functionality")
public void testInsertionSort() {
sortingAlgorithm = new Insertion<Apple>();
testSort(sortingAlgorithm);
//populates random apples
testSort();
//calling sort function
sortingAlgorithm.sort(apples);
//checking if sorted array has any element which is less than preceeding one
assertTrue(test());
}
@Test
@DisplayName("Testing Selection sort functionality")
public void testSelectionSort() {
sortingAlgorithm = new Selection<Apple>();
testSort(sortingAlgorithm);
//populates random apples
testSort();
//calling sort function
sortingAlgorithm.sort(apples);
//checking if sorted array has any element which is less than preceeding one
assertTrue(test());
}
@Test
@DisplayName("Testing Shell sort functionality")
public void testShellSort() {
sortingAlgorithm = new Shell<>();
testSort(sortingAlgorithm);
sortingAlgorithm = new Shell<Apple>();
//populates random apples
testSort();
//calling sort function
sortingAlgorithm.sort(apples);
//checking if sorted array has any element which is less than preceeding one
assertTrue(test());
}
@AfterEach
void tearDown() {
sortingAlgorithm = null;
apples = null;
applesCopy = null;
}
}

View File

@ -2,45 +2,62 @@ package com.hithomelabs.princeton1.module6;
import com.hithomelabs.princeton1.module5.AbstractCustomSorts;
import java.util.Arrays;
import java.util.Random;
public class Merge<E> extends AbstractCustomSorts<E> {
@Override
public void sort(E[] arr) {
int N = arr.length;
// * * aux is a helper array required for merge
E[] aux = Arrays.copyOf(arr, N);
mergesort(arr, aux, 0, N-1);
E[] aux = (E[]) new Object[arr.length];
sort(arr, aux, 0, arr.length-1);
}
private void mergesort(E[] arr, E[] aux, int lo, int hi) {
if (hi <= lo) return;
private void sort(E[] arr,E[] aux, int lo, int hi){
if(hi<=lo) return;
int mid = lo + (hi - lo)/2;
mergesort(arr, aux, lo, mid);
mergesort(arr, aux, mid+1, hi);
merge(arr, aux, lo, mid, hi);
sort(arr,aux, lo, mid);
sort(arr,aux, mid+1,hi);
merge(arr,aux,lo, mid, hi);
}
private void merge(E[] arr, E[] aux, int lo, int mid, int hi) {
private void merge(E[] arr, E[] aux, int lo, int mid, int hi){
// * * creating backup of original array
for (int i = lo; i <= hi; i++)
aux[i] = arr[i];
int i = lo;
int j = mid+1;
for (int k = lo; k <= hi; k++){
// * If i has already reached mid, no need to compare we insert at pointer k
if(i > mid) arr[k] = aux[j++];
else if(j > hi) arr[k] = aux[i++];
else if(less((Comparable<E>) aux[i], aux[j])) arr[k] = aux[i++];
for(int k=lo; k<=hi ;k++)
aux[k] = arr[k];
int i=lo, j = mid+1;
for(int k = lo; k<=hi; k++){
if(i>mid) arr[k] = aux[j++];
else if(j>hi) arr[k] = aux[i++];
else if(less((Comparable<E>) aux[i], aux[j] )) arr[k] = aux[i++];
else arr[k] = aux[j++];
}
}
// public static void main(String[] args){
// Integer[] arrTest = new Integer[6];
//
// for(int i=0;i<6;i++){
// arrTest[i] = new Random().nextInt(100);
// System.out.println(arrTest[i]);
// }
//
// System.out.println();
//
// Merge<Integer> sortAlgo = new Merge<>();
//
// sortAlgo.sort(arrTest);
//
// for(Integer i: arrTest)
// System.out.println(i);
// }
}

View File

@ -2,53 +2,57 @@ package com.hithomelabs.princeton1.module7;
import com.hithomelabs.princeton1.module5.AbstractCustomSorts;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
public class Quick<E> extends AbstractCustomSorts<E> {
@Override
public void sort(E[] arr) {
int N = arr.length;
quickSort(arr, 0, N - 1);
// Collections.shuffle(Arrays.asList(arr));
sort(arr, 0, arr.length-1);
}
public void altSort(E[] arr) {
int N = arr.length;
altQuickSort(arr, 0, N-1);
public void sort(E[] arr, int lo, int hi){
if(lo>=hi) return;
int pivot = partition(arr, lo, hi);
sort(arr, lo, pivot-1);
sort(arr, pivot+1,hi);
}
private void altQuickSort(E[] arr, int lo, int hi) {
if (lo >= hi) return;
int i = lo + 1;
int j = i;
while(j <= hi){
if(less((Comparable<E>) arr[j], arr[lo])){
exch(arr, i, j);
i++;
}
j++;
private int partition(E[] arr, int lo, int hi){
int pivot=lo, i=lo, j=hi+1;
while(i<j){
while(less((Comparable<E>) arr[++i], arr[pivot]))
if(i == hi) break;
while(less((Comparable<E>) arr[pivot], arr[--j]))
if(j == lo) break;
if(i>=j) break;
exch(arr,i, j);
}
exch(arr, i-1, lo);
altQuickSort(arr, lo, i-2);
altQuickSort(arr, i, hi);
exch(arr,pivot,j);
return j;
}
private void quickSort(E[] arr, int lo, int hi) {
if (lo >= hi) return;
int i = lo;
int j = hi+1;
while(true){
while(less((Comparable<E>) arr[++i], arr[lo])){
if(i == hi) break;
}
while(!less((Comparable<E>) arr[--j], arr[lo])){
if (j == lo ) break;
}
if(j<=i) break;
exch(arr, i , j);
}
exch(arr, j, lo);
quickSort(arr, lo, j-1);
quickSort(arr, j+1, hi);
}
// public static void main(String[] args){
// Integer[] arrTest = new Integer[6];
//
// for(int i=0;i<6;i++){
// arrTest[i] = new Random().nextInt(100);
// System.out.println(arrTest[i]);
// }
//
// System.out.println();
//
// Quick<Integer> sortAlgo = new Quick<>();
//
// sortAlgo.sort(arrTest);
//
// for(Integer i: arrTest)
// System.out.println(i);
// }
}

View File

@ -33,6 +33,8 @@ class QuickTest {
Assertions.assertArrayEquals(sorted, arr);
}
// * * Optional test for alternate sort implmentation
/*
@Test
@DisplayName("testing Quick sort default implementation")
public void testAltSort(){
@ -45,6 +47,8 @@ class QuickTest {
Apple[] sorted = apples.toArray(new Apple[apples.size()]);
Assertions.assertArrayEquals(sorted, arr);
}
*/
@AfterEach

21
module8/build.gradle Normal file
View File

@ -0,0 +1,21 @@
plugins {
id 'java'
}
group = 'com.hithomelabs.princeton1.module8'
version = 'unspecified'
repositories {
mavenCentral()
}
dependencies {
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
implementation project(':module5')
testImplementation project(':common')
}
test {
useJUnitPlatform()
}

View File

@ -0,0 +1,35 @@
package com.hithomelabs.princeton1.module8;
/*
* * Designing Heap as a wrapper class with static methods that perform sink and swim operations on underlying comparable[] array
* * Heap does not have any instance variables, instance variables shall be housed by, the implementation using heaps, like priority queues and heap sort
*/
import com.hithomelabs.princeton1.module5.AbstractCustomSorts;
public class Heap{
/*
* * Sink Node T with to it's appropriate place in a Heap of size N, if it's children exist and are greater
* * Implement sink API to sink a node if it's sub-heap is not heap-order
*/
public static <T> void sink(T[] arr, int root, int N){
}
// * * Swim if element is not root, and parent is lesser than node
public static <T extends Comparable<T>> void swim(T[] arr, int node, int N){
}
private static <T> void exch(T[] arr, int i, int j){
T temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
private static <T> boolean less(T v, T w){
if(((Comparable<T>)v).compareTo(w) < 1 ) return true;
else return false;
}
}

View File

@ -0,0 +1,27 @@
package com.hithomelabs.princeton1.module8;
import com.hithomelabs.princeton1.module5.AbstractCustomSorts;
public class HeapSort<E> extends AbstractCustomSorts<E> {
@Override
public void sort(E[] arr) {
int N = arr.length;
E[] heapArr = (E[]) new Object[N+1];
// * * to simplify we copy original array and write it to the new array starting index 1
System.arraycopy(arr, 0, heapArr, 1, N);
// * * An array of size N holds a heap of size N-1
coreSortingLogic(heapArr, N);
// * * Re-copying the sorted array to the original
System.arraycopy(heapArr, 1, arr, 0, N);
}
/*
* * Implement the core sorting logic
* * P.S the provision of making the index 0 null for ease of use has already been done above
*/
private void coreSortingLogic(E[] arr, int N) {
}
}

View File

@ -0,0 +1,51 @@
package com.hithomelabs.princeton1.module8;
import com.hithomelabs.princeton1.common.Apple;
import org.junit.jupiter.api.*;
import java.util.ArrayList;
import java.util.Random;
import static org.junit.jupiter.api.Assertions.*;
class HeapSortTest {
private HeapSort<Apple> heap;
private ArrayList<Apple> apples;
private Random random;
@BeforeEach
void setUp() {
heap = new HeapSort<Apple>();
apples = new ArrayList<Apple>();
random = new Random();
}
@Test
@DisplayName("Sort a heap of a 100 random sized apples")
public void testSort(){
for(int i = 0; i < 100; i++)
apples.add(new Apple(random.nextInt(1000)));
Apple[] arr = apples.toArray(new Apple[apples.size()]);
heap.sort(arr);
apples.sort(null);
Apple[] sorted = apples.toArray(new Apple[apples.size()]);
Assertions.assertArrayEquals(sorted, arr);
}
@Test
@DisplayName("Sort 100 apples in descending order")
public void testSortBorder(){
for(int i = 0; i < 100; i++)
apples.add(new Apple(100 - i));
Apple[] arr = apples.toArray(new Apple[apples.size()]);
heap.sort(arr);
apples.sort(null);
Apple[] sorted = apples.toArray(new Apple[apples.size()]);
Assertions.assertArrayEquals(sorted, arr);
}
@AfterEach
void tearDown() {
}
}

View File

@ -17,4 +17,5 @@ include 'module5'
include 'module6'
include 'common'
include 'module7'
include 'module8'