+ 1

Anyone who can fix the runtime error in my code for insertion in heap?

import java.util.Scanner; import javax.naming.ldap.PagedResultsResponseControl; public class insertionDeletionHeap { // Function to swap two elements public static void swap(int arr[], int i, int parent) { int temp = arr[i]; arr[i] = arr[parent]; arr[parent] = temp; } // Function to insert the element in the heap public static void insert(int arr[], int element) { int n = arr.length; // First increase the size of heap n = n + 1; // insert the new element at the last position of the heap arr[n] = element; // initialize 'i' with the last index of element int i = n; // loop to heapify the inserted element inside the heap to maintain the // properties of max-heap while (i > 0) { // Finding the parent element's index of the inserted element int parent = (i - 1) / 2; // check if new element is greater than its parent then swap them if (arr[i] > arr[parent]) { swap(arr, i, parent); // providing 'i' with the index value of parent element i = parent; } else return; } } // Function to display the elements of the heap public static void display(int arr[]) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } public static void main(String[] args) { // declaring and initialising the max heap int arr[] = { 1, 3, 6, 5, 9, 8 }; Scanner sc = new Scanner(System.in); System.out.println("Enter the element you want to insert in the heap"); int element = sc.nextInt(); // calling the insertion function to insert the element insert(arr, element); // displaying the max heap after insertion of new element display(arr); } }

21st Jul 2022, 10:44 AM
WaseEm BhatTi
WaseEm BhatTi - avatar
2 Antworten
+ 2
first, int[] has fixed size, so arr[arr.length +1] = .. doesn't work, this creates the new bigger array: import java.util.*; ... //n = n + 1; arr = Arrays.copyOf( arr, n+1); then the last index is n
21st Jul 2022, 11:22 AM
zemiak
0
but then for correct return result, you should do //public static void insert(int arr[], int element) { public static int[] insert(int arr[], int element) { //change void to int[] ... } else //return; break; } return arr; //added } ... then in main() //insert(arr, element); arr = insert(arr, element);
21st Jul 2022, 2:20 PM
zemiak