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];
}
}
}
}
Related
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.
Algorithms works some of the time, doesnt work other times. I'm using the JUnit tests found here http://www.vogella.com/tutorials/JavaAlgorithmsMergesort/article.html#mergesort_test
Thanks for any help.
Java Code
package sorting;
public class MergeSort {
public static int[] sort(int[] A) {
mergeSortHelper(A, new int[A.length], 0, A.length - 1);
return A;
}
private static void mergeSortHelper(int[] A, int[] helper, int p, int r) {
if (p < r) {
int mid = (p + r)/2;
mergeSortHelper(A, helper, p, mid);
mergeSortHelper(A, helper, mid + 1, r);
merge(A, helper, p, mid, r);
}
}
private static void merge(int A[], int[] helper, int p, int q, int r) {
for (int i = p; i <= r; i++) {
helper[i] = A[i];
}
int j = p;
int k = q + 1;
int count = 0;
while (j <= q && k <= r) {
if (helper[j] <= helper[k]) {
A[p+count] = helper[j++];
} else {
A[p+count] = helper[k++];
}
count++;
}
while (j <= q) {
A[p+count] = A[j++];
count++;
}
while (k <= r) {
A[p+count] = A[k++];
count++;
}
}
}
JUnit
package tests;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.Random;
import org.junit.Before;
import org.junit.Test;
import sorting.MergeSort;
public class MergeSortTest {
private int[] numbers;
private final static int SIZE = 7;
private final static int MAX = 20;
#Before
public void setUp() throws Exception {
numbers = new int[SIZE];
Random generator = new Random();
for (int i = 0; i < numbers.length; i++) {
numbers[i] = generator.nextInt(MAX);
}
}
#Test
public void testMergeSort() {
long startTime = System.currentTimeMillis();
MergeSort.sort(numbers);
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Mergesort " + elapsedTime);
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
fail("Should not happen");
}
}
assertTrue(true);
}
#Test
public void itWorksRepeatably() {
for (int i = 0; i < 200; i++) {
numbers = new int[SIZE];
Random generator = new Random();
for (int a = 0; a < numbers.length; a++) {
numbers[a] = generator.nextInt(MAX);
}
MergeSort.sort(numbers);
for (int j = 0; j < numbers.length - 1; j++) {
if (numbers[j] > numbers[j + 1]) {
fail("Should not happen");
}
}
assertTrue(true);
}
}
#Test
public void testStandardSort() {
long startTime = System.currentTimeMillis();
Arrays.sort(numbers);
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Standard Java sort " + elapsedTime);
for (int i = 0; i < numbers.length - 1; i++) {
if (numbers[i] > numbers[i + 1]) {
fail("Should not happen");
}
}
assertTrue(true);
}
}
Wrong:
while (j <= q) {
A[p+count] = A[j++];
count++;
}
while (k <= r) {
A[p+count] = A[k++];
count++;
}
Corrected:
while (j <= q) {
A[p+count] = helper[j++];
count++;
}
while (k <= r) {
A[p+count] = helper[k++];
count++;
}
I modified the code :) to pass tests but I'm not sure if it's 100% secure code. Use it at your own risk.
package sorting;
public class MergeSort {
public static int[] sort(int[] A) {
mergeSortHelper(A, new int[A.length], 0, A.length - 1);
return A;
}
private static void mergeSortHelper(int[] A, int[] helper, int p, int r) {
if (p < r) {
int mid = (p + r)/2;
mergeSortHelper(A, helper, p, mid);
mergeSortHelper(A, helper, mid + 1, r);
merge(A, helper, p, mid, r);
}
}
private static void merge(int A[], int[] helper, int p, int q, int r) {
for (int i = p; i <= r; i++) {
helper[i] = A[i];
}
int j = p;
int k = q + 1;
int count = 0;
while (j <= q && k <= r) {
if (helper[j] < helper[k]) {
A[p+count] = helper[j++];
} else {
A[p+count] = helper[k++];
}
count++;
}
while (j <= q) {
A[p+count++] = helper[j++];
}
while (k <= r) {
A[p+count++] = helper[k++];
}
}
}
These are the changes incured
diff --git a/src/sorting/MergeSort.java b/src/sorting/MergeSort.java
index 0f5c8e4..dbf6689 100644
--- a/src/sorting/MergeSort.java
+++ b/src/sorting/MergeSort.java
## -35,7 +35,7 ##
int count = 0;
while (j <= q && k <= r) {
- if (helper[j] <= helper[k]) {
+ if (helper[j] < helper[k]) {
A[p+count] = helper[j++];
} else {
A[p+count] = helper[k++];
## -45,13 +45,11 ##
}
while (j <= q) {
- A[p+count] = A[j++];
- count++;
+ A[p+count++] = helper[j++];
}
while (k <= r) {
- A[p+count] = A[k++];
- count++;
+ A[p+count++] = helper[k++];
}
}
}
\ No newline at end of file
// https://github.com/kangchen/SortAlgorithm
import java.util.ArrayList;
import java.util.List;
public final class MergeSort implements Runnable, Sort {
private List<Integer> list;
private List<Integer> temp = new ArrayList<Integer> ();
private long time = 0;
private boolean sortCompleted = false;
public MergeSort(List<Integer> item) {
this.list = item;
initializeTempList();
}
public void run() {
sort();
System.out.println(this.toString());
}
private void initializeTempList() {
for(int i=0; i<list.size(); i++) {
temp.add(0);
}
}
/*
* Merge Sort Algorithm O(N*LOGN)
*/
public void sort() {
long starttime = System.nanoTime();
mergePartition(0, list.size()-1);
long endtime = System.nanoTime();
time = endtime - starttime;
sortCompleted = true;
}
private void mergePartition(int low, int high) {
if (low == high) return;
else {
int mid = (low + high) / 2;
mergePartition(low, mid);
mergePartition(mid+1, high);
merge(low, mid+1, high);
}
}
private void merge(int lowPtr, int midPtr, int highPtr) {
int ci = 0;
int ai = lowPtr;
int mid = midPtr - 1;
int bi = highPtr - ai + 1;
while (lowPtr <= mid && midPtr <= highPtr) {
if (list.get(lowPtr) < list.get(midPtr)) {
temp.set(ci++, list.get(lowPtr++));
}
else {
temp.set(ci++, list.get(midPtr++));
}
}
/*
* copy remaining sorted elements
*/
while (lowPtr <= mid) {
temp.set(ci++, list.get(lowPtr++));
}
/*
* copy remaining sorted elements
*/
while (midPtr <= highPtr) {
temp.set(ci++, list.get(midPtr++));
}
/*
* replace original elements with sorted elements
*/
copy(ai, bi, temp);
}
private void copy(int from, int num, List<Integer> arrTemp) {
for(int i=0; i<num; i++){
list.set(from+i, arrTemp.get(i));
}
}
public long getTime() {
return time;
}
public String toString() {
return "Merge sort is completed in " + getTime() + " nanoseconds";
}
private void swap(int x, int y) {
int tmp = list.get(x);
list.set(x, list.get(y));
list.set(y, tmp);
}
public void reversedList() {
int idx = list.size()/2;
int high = list.size()-1;
for(int low=0; low<idx; low++) {
swap(low, high--);
}
}
public boolean isSortCompleted() {
return sortCompleted;
}
}
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
Sorry if my question is not clear, lets say I have int a = 1234;.
How can I print as follows, for a number of any length?
123
132
213
231
321
312
Thanks in advance.
public class Test {
private static void swap(int[] p, int i, int j) {
int t= p[i];
p[i]= p[j];
p[j]= t;
return;
}
private static boolean nextPerm(int[] p) { // need p.length > 1
int n= p.length;
int i= n;
if (i-- < 1) return false;
for(;;) {
int ii= i--;
if (p[i] < p[ii]) {
int j= n;
while (!(p[i] < p[--j]));
swap(p, i, j);
for (j= n; j > ii; swap(p, --j, ii++));
return true;
}
if (i == 0) {
for (int j= n; j > i; swap(p, --j, i++));
return false;
}
}
}
public static void main(String[] args) {
int x = 123;
String s = "" + x;
int n = s.length();
int[] p = new int[n];
for (int i = 0; i < n; i++){
p[i] = i;
}
do {
for (int i = 0; i < n; i++){
System.out.print(s.charAt(p[i]));
}
System.out.println();
}
while (nextPerm(p));
}
}
finally I found, below is the code,
class ShuffleNumber {
private static int[] a = {1,2,3};
private static void print(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(" " + a[i]);
System.out.println();
}
private static void shuffle(){
int[] b = (int[])a.clone();
for (int i = b.length - 1; i > 0; i--) {
int j = (int)Math.floor(Math.random() * (i+1));
int temp = b[j];
b[j] = b[i];
b[i] = temp;
}
print(b);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
shuffle();
}
}
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.