I am new to java. I wrote a program to sort an array using bubblesort algorithm.I have 3 methods getArray()
, putArray()
& sortArray()
. I have called all these methods from the main
function passing the no of elements and an array as parameters. I have passed a null array to getArray()
function and got the array as input from the user. When i get the input i get exception. Kindly help me out. I am literally stranded.`
import java.util.Scanner;
public class BubbleSort {
public void getArray(int num,int[]arr) {
System.out.print("Enter the total number of elements in the Array : ");
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
System.out.println(num);
System.out.print("Enter " + num + " Elements : ");
for (int i = 0; i < num; i++) {
arr[i] = sc.nextInt();
}
}
public void putArray(int num,int[] arr) {
System.out.print("The Array is: ");
for (int i = 0; i < num; i++) {
System.out.println(arr[i] + " ");
}
}
public void sortArray(int num,int[] arr) {
for (int i = 0; i < num; i++) {
boolean flag = false;
for (int j = 0; j < num - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
arr[j] = arr[j] + arr[j + 1];
arr[j + 1] = arr[j] - arr[j + 1];
arr[j] = arr[j] - arr[j + 1];
flag = true;
}
}
if (!flag) {
break;
}
}
}
public static void main(String[] args) {
int num=0;
int[] arr=null;
BubbleSort b = new BubbleSort();
b.getArray(num,arr);
b.putArray(num,arr);
b.sortArray(num,arr);
b.putArray(num,arr);
}
}