Skip to content
Snippets Groups Projects
Commit f6d6996e authored by Eetu Kumpulainen's avatar Eetu Kumpulainen
Browse files

Merge branch 'heapsort' into main

parents 2b87f5ee 2ee98b51
No related branches found
No related tags found
No related merge requests found
Checking pipeline status
package algorithmcomparison;
public class Heapsort {
// Class where data is sorted with heap sort
public static int[] sort(int data[]) {
int arr[] = data.clone();
// Build heap (rearrange array)
for (int i = arr.length / 2 - 1; i >= 0; i--)
heapify(arr, arr.length, i);
// One by one extract an element from heap
for (int i = arr.length - 1; i > 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
return arr;
}
public static void heapify(int arr[], int n, int i)
{
int biggest = i; // Initialize biggest as root
int left = 2 * i + 1; // left = 2*i + 1
int right = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (left < n && arr[left] > arr[biggest])
biggest = left;
// If right child is larger than largest so far
if (right < n && arr[right] > arr[biggest])
biggest = right;
// If largest is not root
if (biggest != i) {
int swap = arr[i];
arr[i] = arr[biggest];
arr[biggest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, biggest);
}
}
}
package algorithmcomparison;
import net.jqwik.api.*;
import java.util.Arrays;
public class HeapsortTests {
/**
*Tests if heapsort sorts the dataset correctly
*
* @param arr The given test array
*
* @return True if sorts correctly, otherwise returns false
*/
@Property
boolean must_sort_correctly(@ForAll("array") Integer[] arr) {
int[] intArray = Arrays.stream(arr).mapToInt(Integer::intValue).toArray();
int[] sorted = Heapsort.sort(intArray);
Arrays.sort(intArray);
return Arrays.equals(intArray, sorted);
}
/**
*Generates the test dataset
*
*@return The test dataset
*/
@Provide
Arbitrary<Integer[]> array() {
Arbitrary<Integer> integerArbitrary = Arbitraries.integers().between(1, 100);
return integerArbitrary.array(Integer[].class).ofSize(100);
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment