This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
So I am sort of new to Java and have only been doing it for a couple of months. I'm trying to implement different types of sorting algorithms and I think everything is okay except when I run it I get a NullPointerException on the for loop. I have already read this post What is a NullPointerException, and how do I fix it?. But I still can not figure out how to fix the problem even though I think it is quite simple. Any help?
import java.lang.*;
import java.util.*;
public class SortApp {
public int[] generateRandomArray(int size) {
int[] output = new int[size];
for (int i = 0; i < size; i++) {
output[i] = (int) (Math.random() * Integer.MAX_VALUE);
}
return output;
}
public void printArray(int[] inarray) {
for (int i = 0; i < inarray.length; i++) {
System.out.println(inarray[i]);
}
}
public boolean isSorted(int[] inarray) {
for (int i = 0; i < inarray.length; i++) { //Error here
if (inarray[i] > inarray[i + 1]) {
return false;
}
}
return true;
}
public int[] insertionSort(int[] inarray) {
int[] data = Arrays.copyOf(inarray, inarray.length);
int temp;
int j;
for (int i = 0; i < inarray.length; i++) {
temp = inarray[i];
for (j = 0; (j > 1) && (temp < inarray[j - 1]); j--)
inarray[j] = inarray[j - 1];
inarray[j] = temp;
}
return data;
}
public int[] selectionSort(int[] inarray) {
int[] data = Arrays.copyOf(inarray, inarray.length);
int temp;
int n = inarray.length;
for (int i = 0; i < inarray.length; i++) {
int k = i;
for (int j = i + 1; j < n; j++)
if (inarray[j] < inarray[k])
k = j;
temp = inarray[i];
inarray[i] = inarray[k];
inarray[k] = temp;
}
return data;
}
public int[] mergeSort(int[] inarray, int temp[], int l, int r) {
int[] data = Arrays.copyOf(inarray, inarray.length);
if (l == r) return null;
int mid = (l + r) / 2;
mergeSort(inarray, temp, l, mid);
mergeSort(inarray, temp, mid + 1, r);
int i, j, k;
for (i = l; i <= r; i++)
temp[i] = inarray[i];
for (i = l, j = mid + 1, k = l; i <= mid && j <= r && k <= r; k++)
if (temp[i] < temp[j]) inarray[k] = temp[i];
i++;
inarray[k] = temp[j];
j++;
for (; i <= mid; i++, k++)
inarray[k] = temp[i];
for (; j <= r; j++, k++)
inarray[k] = temp[j];
return data;
}
public static void main(String[] args) {
SortApp myApp = new SortApp();
int[] data = myApp.generateRandomArray(10);
boolean isSortedA = myApp.isSorted(myApp.insertionSort(data));
boolean isSortedB = myApp.isSorted(myApp.selectionSort(data));
boolean isSortedC = myApp.isSorted(myApp.mergeSort(data, data, 0, 0)); //Error here
myApp.printArray(data);
}
}
Error I am getting is this:
Exception in thread "main" java.lang.NullPointerException
at SortApp.isSorted(SortApp.java:23)
at SortApp.main(SortApp.java:91)
It's because of this line:
if (l==r) return null;
You are passing in 0 for both l and r meaning they are equal. Therefore, you are getting a null value passed in to your isSorted() call.
Related
My methods below are to fix the heap order.
private void upHeap(int i) {
// TO DO Implement this method
int temp = 0;
int n = heap.length-1;
for(int j=n;j>0;j--){
if(heap[j]>heap[parent(j)]){ //if current index is greater than its parent, swap
temp = heap[j]; //use a temporary variable to help
heap[j] = heap[parent(j)];
heap[parent(j)] = temp;
upHeap(heap[parent(j)]);
}
}
}
And the down heap
private void downHeap(int i) {
// TO DO Implement this method
int temp = 0;
for(int j=i; j<heap.length; j++){
if(heap[i]<heap[j]){
temp = heap[j];
heap[j] = heap[i];
heap[i] = temp;
}
}
}
It is a maxHeap, so the numbers should be descending. Can anybody see in my code where I've gone wrong? It is now giving me an index out of bounds error.
Try these:
private void upHeap(int i) {
int temp = 0;
for (int j = i; j >= 0; j--) {
for (int k = j - 1; k >= 0; k--) {
if (heap[j] > heap[k]) {
temp = heap[j];
heap[j] = heap[k];
heap[k] = temp;
} else {
break;
}
}
}
}
private void downHeap(int i) {
int temp = 0;
for (int j = i; j < heap.length; j++) {
for (int k = j + 1; k < heap.length; k++) {
if (heap[k] > heap[j]) {
temp = heap[j];
heap[j] = heap[k];
heap[k] = temp;
} else {
break;
}
}
}
}
The code still error, even though I have already fixed almost half the program
this initialized at main class:
Getting the below error:
Exception in thread "main"
java.lang.NullPointerException
at Tugas7.No3.seqSearch(No3.java:72)
at Tugas7.No3Main.main(No3Main.java:27)
what are you expecting to get out?
I excepting the code when run can search the number
package Tugas7;
public class No3 {
public int[] data;
public int jumData,min,max;
;
public int baris, kolom, posisiBar, posisiKol, posisi;
public void No3(int[] data) {
sort(data, 0, 8);
}
private void merge(int[] data, int left, int middle, int right) {
int[] temp = new int[data.length];
for (int i = left; i <= right; i++) {
temp[i] = data[i];
}
int a = left;
int b = middle + 1;
int c = left;
while (a <= middle && b <= right) {
if (temp[a] <= temp[b]) {
data[c] = temp[a];
a++;
} else {
data[c] = temp[b];
b++;
}
c++;
}
int s = middle - a;
for (int i = 0; i <= s; i++) {
data[c + i] = temp[a + i];
}
}
private void sort(int data[], int left, int right) {
if (left < right) {
int middle = (left + right) / 2;
sort(data, left, middle);
sort(data, middle + 1, right);
merge(data, left, middle, right);
}
}
public void printArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public int[] Searching(int[] Data, int jmlData) {
this.jumData = 10;
data = new int[jumData];
for (int i = 0; i < jumData; i++) {
data[i] = Data[i];
}
return data;
}
public int seqSearch(int cari) {
this.posisi = -1;
for (int j = 0; j < 11; j++) {
if (data[j] == cari) {
posisi = j;
break;
}
}
return posisi;
}
public void TampilData() {
for (int i = 0; i < 10; i++) {
System.out.print(data[i] + " ");
}
System.out.println();
}
public void searchMax(int[] data) {
min = data[0];
max = data[0];
for (int i = 0; i < 10; i++) {
if (data[i] < min) {
min = data[i];
} else if (data[i] > max) {
max = data[i];
}
}
}
}
I have just written up this code an have been trying for ages to try and find out why it is not printing the sorted list. It is running and there are no bugs, except it just does not print out the sorted list. Can you please help me find whats wrong?
public class Merging {
public static void main(String[] args) {
int[] a = new int[10];
populate(a);
printA(a);
a = merge_sort(a);
printA(a);
}
public static int[] merge_sort(int[] B) {
if (B.length <= 1) {
return B;
}
int midpoint = B.length / 2;
int[] left = new int[midpoint];
int[] right= new int[B.length-midpoint];
int[] result;
for (int i = 0; i < midpoint; i++) {
left[i] = B[i];
}
int x = 0;
for (int j = midpoint; j < B.length; j++) {
if (x < right.length) {
right[x] = B[j];
x++;
}
}
left = merge_sort(left);
right = merge_sort(right);
result = merge(left, right);
return result;
}
public static int[] merge(int[] left, int[] right) {
int lengthResult = left.length + right.length;
int[] result = new int[lengthResult];
int indexL = 0;
int indexR = 0;
int indexRes = 0;
while (indexL < left.length || indexR < right.length) {
if (indexL < left.length && indexR < right.length) {
if (left[indexL] <= right[indexR]) {
result[indexRes] = left[indexL];
indexL++;
indexRes++;
} else {
result[indexRes] = right[indexR];
indexR++;
indexRes++;
}
} else if (indexL < left.length) {
result[indexRes] = left[indexL];
indexL++;
indexRes++;
}
}
return result;
}
public static void printA(int[] B) {
for (int i = 0; i < B.length; i++) {
System.out.print(B[i] + " ");
}
}
public static int[] populate(int[] B) {
for (int i = 0; i < B.length; i++) {
B[i] = (int) (Math.random() * 100);
}
return B;
}
}
imagine the case in your loop, where indexL < left.length == false but indexR < right.length == true, you never increase indexR and the loop will never terminate
I am writing code for a bottom-up mergeSort in Java. Right now, I think there may be an indexing issue with the call to merge, but I am having trouble figuring out exactly what my problem is. Any assistance would be greatly appreciated!
public static int[] merge(int[]a, int lo1, int hi1, int lo2, int hi2) {
int[]b = new int[hi2-lo1+1];
int i = lo1;
int j = lo2;
int k = 0;
while (i <= hi1 && j <= hi2) {
if(a[i] < a[j])
b[k++] = a[i++];
else
b[k++]=a[j++];
}
while (i <= hi1)
b[k++] = a[i++];
while (j <= hi2)
b[k++] = a[j++];
for (int l = 0; l < k; l++)
a[lo1 + l] = b[l];
return a; //added
}
public static int[] betterMergeSort(int[]a, int lo, int hi){
for (int comparesize=1; comparesize < (hi-lo+1); comparesize*=2) {
for (int k=lo; k < hi; k+=2*comparesize) {
int[]holder = new int[Math.min(k+2*comparesize-1,hi)-lo+1];
holder = merge(a, k, k+comparesize-1, k+comparesize, Math.min(k+2*comparesize-1, hi));
if (holder.length == (hi-lo+1)){
for (int j=0; j<(hi-lo+1); j++)
a[lo+j] = holder[j];
}
}
}
return a;
}
Note that I need this code to return int[] for now in order to check its accuracy.
Question: Where are comparisons being made in each separate sorting method?
Also if you know please tell me which method count numbers are wrong and where to place my counters instead.trying to understand where and how many times sorting methods make comparisons.
Method A B
Selection 4950 4950
Bubble 99 9900
Insertion 99 5049
Merge 712 1028
Shell 413 649
Quick 543 1041
Okay so to explain some parts, basically Array A is an array from 1-100 in ascending order. So this should be the minimum number of comparisons.
Array B is 100-1 in descending order. So I believe it should be the maximum number of comparisons. Array C is just randomly generated numbers, so it changes every time.
I feel like my selection and bubble sorts were counted correctly. Feel free to let me know where comparisons are being made that I haven't counted, or if I'm counting wrong comparisons.
Side note: Made some global variable to count the methods that were recursive in multiple sections.
class Sorting
{
static int[] X = new int[100];
static int mergecount = 0;
static int quickcount = 0;
public static void selectionSort(int list[])
{
int count = 0;
int position = 0, n = list.length;
for(int j = 0; j < n-1; j++)
{
position = j;
for(int k = j+1; k < n; k++)
{
count++;
if(list[k] < list[position])
position = k;
}
Swap(list, j, position);
}
System.out.println("counter" + count);
}
public static void Swap(int list[], int j, int k)
{
int temp = list[j];
list[j] = list[k];
list[k] = temp;
}
public static void bubbleSort(int list[])
{
int count = 0;
boolean changed = false;
do
{
changed = false;
for(int j = 0; j < list.length - 1; j++)
{
count++;
if(list[j] > list[j + 1])
{
Swap(list, j, j+1);
changed = true;
}
}
} while(changed);
System.out.println("counter" + count);
}
public static void insertionSort(int list[])
{
int count = 0;
for(int p = 1; p < list.length; p++)
{
int temp = list[p];
int j = p;
count++;
for( ; j > 0 && temp < list[j - 1]; j = j-1)
{
list[j] = list[j - 1];
count++;
}
list[j] = temp;
}
System.out.println("counter" + count);
}
public static void mergeSort(int list[])
{
mergeSort(list, 0, list.length - 1);
System.out.println("counter" + mergecount);
}
public static void mergeSort(int list[], int first, int last)
{
if(first < last)
{
int mid = (first + last) / 2;
mergeSort(list, first, mid);
mergeSort(list, mid + 1, last);
Merge(list, first, mid, last);
}
}
public static void Merge(int list[], int first, int mid, int last)
{
int count = 0;
int first1 = first, last1 = mid;
int first2 = mid + 1, last2 = last;
int temp[] = new int[list.length];
int index = first1;
while(first1 <= last1 && first2 <= last2)
{
if(list[first1] < list[first2])
{
temp[index] = list[first1++];
mergecount++;
}
else
temp[index] = list[first2++];
index++;
mergecount++;
}
while(first1 <= last1)
temp[index++] = list[first1++];
while(first2 <= last2)
temp[index++] = list[first2++];
for(index = first; index <= last; index++)
list[index] = temp[index];
}
public static void shellSort(int list[])
{
int count = 0;
int n = list.length;
for(int gap = n / 2; gap > 0; gap = gap == 2 ? 1: (int) (gap/2.2))
for(int i = gap; i < n; i++)
{
int temp = list[i];
int j = i;
count++;
for( ; j >= gap && (temp < (list[j - gap])); j -= gap)
{
list[j] = list[j - gap];
count++;
}
list[j] = temp;
}
System.out.println("counter" + count);
}
public static void quickSort(int start, int finish, int list[])
{
int count = 0;
int left = start, right = finish, pivot, temp;
pivot = list[(start + finish) / 2];
do
{
while(list[left] < pivot)
{
left++;
quickcount++;
}
while(pivot < list[right])
{
right--;
quickcount++;
}
if(left <= right)
{
temp = list[left];
list[left++] = list[right];
list[right--] = temp;
quickcount++;
}
} while(left < right);
if(start < right)
quickSort(start, right, list);
if(left < finish)
quickSort(left, finish, list);
}
public static void copy(int list[])
{
for(int i = 0; i < list.length; i++)
X[i] = list[i];
}
public static void restore(int list[])
{
for(int i = 0; i < list.length; i++)
list[i] = X[i];
}
public static void displayArray(int list[])
{
for(int k = 0; k < list.length; k++)
System.out.print(list[k] + " ");
System.out.println();
}
public static void main(String args[])
{
int[] A = new int[100];
for(int i = 0; i < A.length; i++)
A[i] = i + 1;
int[] B = new int[100];
int q = 100;
for(int i = 0; i < B.length; i++)
B[i] = q--;
int[] C = new int[100];
for(int i = 0; i < C.length; i++)
C[i] = (int)(Math.random() * 100 + 1);
displayArray(A);
copy(A);
selectionSort(A);
displayArray(A);
restore(A);
}
Note that QuickSort performance is greatly influenced by your choice of the pivot. With both of your test arrays sorted (ascending / descending) and because you are picking pivot as array[length/2] you are actually always picking the best pivot. So your test case B won't generate maximum number of comparisons for quicksort. If you were picking array[0] as pivot you'd get maximum number of comparisons for test case A and B.
The easiest way to count comparisons is to use a compare function and do it in there.
static int compareCount = 0;
int compareInt(int a, int b) {
compareCount++;
return a - b; // if 0 they are equal, if negative a is smaller, if positive b is smaller
}
Now just use compareInt in all your algorithms and you'll get an accurate count. You'll have to reset compareCount between each run though.