File tree Expand file tree Collapse file tree
Heap_Sort/Java/rrivera1849 Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11/*
22 * Written by: Rafael A. Rivera Soto
3- * Last Updated: January 2, 2013
3+ * Last Updated: January 2, 2014
44 *
55 * This class only contains the necessary methods needed to build a maxHeap and sort
66 * our array. It is in no way representative of a real heap implementation.
Original file line number Diff line number Diff line change 1+ /*
2+ * Written by: Rafael A. Rivera Soto
3+ * Last Updated: January 2, 2013
4+ *
5+ * This class only contains the necessary methods needed to build a maxHeap and sort
6+ * our array. It is in no way representative of a real heap implementation.
7+ */
8+ public class Heap {
9+ int [] array;
10+ int size;
11+
12+ public Heap(int[] array) {
13+ this.array = array;
14+ this.size = array.length;
15+ buildMaxHeap();
16+ }
17+
18+ public int leftIndex(int i){
19+ return 2*i + 1;
20+ }
21+
22+ public int rightIndex(int i){
23+ return 2*i + 2;
24+ }
25+
26+ public void swap(int index1, int index2){
27+ int temp = array[index1];
28+ array[index1] = array[index2];
29+ array[index2] = temp;
30+ }
31+
32+ public void maxHeapify(int i){
33+ int l = leftIndex(i);
34+ int r = rightIndex(i);
35+ int largest;
36+
37+ if(l < size && array[l] > array[i]){
38+ largest = l;
39+ }else{
40+ largest = i;
41+ }
42+
43+ if(r < size && array[r] > array[largest]){
44+ largest = r;
45+ }
46+
47+ if(largest != i){
48+ swap(i,largest);
49+ maxHeapify(largest);
50+ }
51+ }
52+
53+ public void buildMaxHeap(){
54+ for(int i = size/2 - 1; i >= 0; i--){
55+ maxHeapify(i);
56+ }
57+ }
58+
59+ public int[] getArray(){
60+ return array;
61+ }
62+ }
Original file line number Diff line number Diff line change 11/*
22 * Written by: Rafael A. Rivera Soto
3- * Last Updated: January 2, 2013
3+ * Last Updated: January 2, 2014
44 */
55public class Heap_Sort {
66 /*
Original file line number Diff line number Diff line change 1+ /*
2+ * Written by: Rafael A. Rivera Soto
3+ * Last Updated: January 2, 2013
4+ */
5+ public class Heap_Sort {
6+ /*
7+ * Description:
8+ * Represents the array as a heap in order to effectively sort it. Uses functions
9+ * implemented in the heap class in order to build the heap as a "max heap" and then
10+ * sort.
11+ *
12+ * Input:
13+ * array:int - sequence to sort
14+ *
15+ * Output:
16+ * A sorted array.
17+ *
18+ * Complexity:
19+ * O(nln(n))
20+ */
21+ public static int[] heapSort(int[] array){
22+ Heap arrayHeap = new Heap (array);
23+
24+ for(int i = arrayHeap.size - 1; i > 0; i--){
25+ arrayHeap.swap(i, 0);
26+ arrayHeap.size -= 1;
27+ arrayHeap.maxHeapify(0);
28+ }
29+
30+ return arrayHeap.getArray();
31+ }
32+ }
You can’t perform that action at this time.
0 commit comments