Please let me know the issue i have in this short code. I tried to follow the algo from the book and convert it into a program but have done some error in the process. Its throwing arrayoutofbounds exception
Algo which i tried to follow is bellow:
countingsort(a,b,k)
1)let c[0..k] be a new array
2)for i =0 to k
3) c[i]=0;
4)for j=1 to a.length
5) c[a[j]]=c[a[j]]+1
6)for i = i to k
c[i] = c[i] + c[i-1]
7)for j=a.length downto 1
b[c[a[j]]]= a[j]
c[a[j]] = c[a[j]]-1
public class CountingSort {
public static void main(String[] args) {
int[] array_A = {6, 0, 2, 0, 1, 3, 4, 6, 1, 3, 2};
int[] array_B = new int[array_A.length];
int k = 6;
countingSort(array_A,array_B,k);
//System.out.println(array_B);
}
public static void countingSort(int[] A, int[] B, int k){
int[] C = new int[k+1];
for(int i = 0; i<=k; i++){
C[i] = 0;
}
for(int j = 0; j<A.length; j++){
C[A[j]] = C[A[j]] + 1;
}
for(int i = 1; i<=k; i++){
C[i] = C[i] + C[i-1];
}
for(int j = A.length-1; j>=1; j--){
B[C[A[j]]] = A[j];
C[A[j]] = C[A[j]] - 1;
}
System.out.println(Arrays.toString(B));
}
}
Error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 11
at importantPrograms.CountingSort.countingSort(CountingSort.java:22)
at importantPrograms.CountingSort.main(CountingSort.java:11)
Here is the modified code that worked for me.
import java.util.Arrays;
public class CountingSort {
public static void main(String[] args) {
int[] array_A = {6, 0, 2, 0, 1, 3, 4, 6, 1, 3, 2};
int[] array_B = new int[array_A.length];
int k = 6;
countingSort(array_A,array_B,k);
System.out.println(Arrays.toString(array_B));
}
public static void countingSort(int[] A, int[] B, int k){
int[] C = new int[k+1];
for(int i = 0; i<=k; i++){
C[i] = 0;
}
for(int j = 0; j<A.length; j++){
C[A[j]] ++;
}
for(int i = 1; i<=k; i++){
C[i] += C[i-1];
}
for(int j = A.length-1; j>=0; j--){
B[--C[A[j]]] = A[j];
}
}
}
Ideally, instead of hard-coding the max value (6), you would find the max programmatically and size your count array accordingly. Such as
In main method
countingSort(array_A,array_B,max(array_A));
Max method
public int max(int[] arr){
int m = 0;
for(int i : arr){
if(i>m){
m = i;
}
}
return m;
}
Change
C[A[j]] = C[A[j] + 1]; to C[A[j]] = C[A[j]] + 1; because you are supposed to count the number of particular number occurrence.
I have no clue what you are doing but there is only a little mistake in your second for loop.
Change j<A.length to j<C.length
Related
I'm trying to copy a 1 by 9 array into a 3 by 3 array. I'm not sure why my output is just the number 1 moving across the array. Any help would be greatly appreciated.
public class arrayTest{
public static void main(String [] args)
{
int A [] = {1,2,3,4,5,6,7,8,9};
int B [][] = new int [3][3];
int i = 0, k, j;
for(k = 0; k < 3; k++)
for(j = 0; j < 3; j++ ){
B[k][j] = A[i];
k++;
}
for(k = 0; k < 3; k++)
{
for(j = 0; j< 3; j++)
System.out.print(B[k][j] + " ");
System.out.println();
}
}
}
You need to convert the 2D coordinates from the loop counters into an index into the 1D array:
int A [] = {1,2,3,4,5,6,7,8,9};
int B [][] = new int [3][3];
for (int k=0; k < 3; k++) {
for (int j=0; j < 3; j++) {
B[k][j] = A[k*3 + j];
}
}
System.out.println(Arrays.deepToString(B));
// [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
public class array12 {
static void merge_sort(int A[], int start, int end) {
if (end - start > 1) {
int middle1 = (2 * start + end + 1) / 3 - 1;
int middle2 = 2 * middle1 - start + 1;
merge_sort(A, start, middle1);
merge_sort(A, middle1 + 1, middle2);
merge_sort(A, middle2 + 1, end);
merge(A, start, middle1, middle2, end);
}
}
static void merge(int[] x, int start, int middle1, int middle2, int end) {
int n1 = middle1 - start + 1;
int n2 = middle2 - middle1;
int n3 = end - middle2;
int left[] = new int[n1]; // defining and initialising three arrays .
int mid[] = new int[n2];
int right[] = new int[n3];
for (int i = 0; i < left.length; i++) {
left[i] = x[i + start];
}
for (int i = 0; i < mid.length; i++) {
mid[i] = x[i + middle1 + 1];
}
for (int i = 0; i < right.length; i++) {
right[i] = x[i + middle2 + 1];
}
int i = 0;
int j = 0;
int k = 0;
int c = start;
// finding minimum element from the three arrays .
while (i < n1 && j < n2 && k < n3) {
if (left[i] <= mid[j] && left[i] <= right[k]) {
x[c] = left[i];
i++;
c++;
} else if (mid[j] <= left[i] && mid[j] <= right[k]) {
x[c] = mid[j];
j++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
// now only two arrays are left to be compared
while (i < n1 && j < n2) {
if (left[i] <= mid[j]) {
x[c] = left[i];
i++;
c++;
} else {
x[c] = mid[j];
j++;
c++;
}
}
while (j < n2 && k < n3) {
if (mid[j] <= right[k]) {
x[c] = mid[j];
j++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
while (i < n1 && k < n3) {
if (left[i] <= right[k]) {
x[c] = left[i];
i++;
c++;
} else {
x[c] = right[k];
k++;
c++;
}
}
// now only single array is left out of left[] , mid[] and right[].
while (i < n1) {
x[c] = left[i];
i++;
c++;
}
while (j < n2) {
x[c] = mid[j];
j++;
c++;
}
while (k < n3) {
x[c] = right[k];
k++;
c++;
}
System.out.println("");
// printing array elements after every merge operation .
for (int e = 0; e < x.length; e++) {
System.out.print(x[e] + " ");
}
}
public static void main(String[] args) {
int[] x = new int[9];
for (int i = 0; i < x.length; i++) {
x[i] = x.length - i;
}
System.out.println("initial array is : ");
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
System.out.println("");
merge_sort(x, 0, x.length - 1);
System.out.println("");
System.out.println("");
System.out.println(" sorted array is : ");
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
}
I am trying to merge 3 sorted arrays . I have been able to develop code for array size equal to power of 3 . I am unable to implement it with some other array size . I have tried to change values of middle1 and middle2 but am experiencing serious trouble . Setting their values is the main concern . Merging step is quite simple and is not causing problems .
What changes are required in my code so that it may work for any array size ? Can it be implemented using this approach ? I dont want size of any of the three arrays , left[] , mid[] and right[] to be zero at any time .
Please help .
Here's a similar answer to YCF_L's, but simplified (still uses Java 8):
public static int[] sortMultipleArrays(int[]... arrays) {
return Arrays.stream(arrays)
.flatMapToInt(Arrays::stream)
.sorted()
.toArray();
}
Output:
[1, 2, 3, 5, 6, 7, 9, 10, 12, 13, 17, 20, 21, 24]
I don't follow your merge code. It seems overly complicated.
Here is a method for merging an unlimited number of sorted arrays, each a varying size.
private static int[] mergeSortedArrays(int[]... arrays) {
int totalLen = 0;
for (int[] arr : arrays)
totalLen += arr.length;
int[] idx = new int[arrays.length];
int[] merged = new int[totalLen];
for (int i = 0; i < totalLen; i++) {
int min = 0, minJ = -1;
for (int j = 0; j < arrays.length; j++)
if (idx[j] < arrays[j].length)
if (minJ == -1 || min > arrays[j][idx[j]]) {
min = arrays[j][idx[j]];
minJ = j;
}
merged[i] = min;
idx[minJ]++;
}
return merged;
}
Test
int[] a = { 3, 5, 9, 13, 17, 21 };
int[] b = { 2, 10, 20 };
int[] c = { 1, 7, 12, 24 };
int[] d = { 6 };
int[] merged = mergeSortedArrays(a, b, c, d);
System.out.println(Arrays.toString(merged));
Output
[1, 2, 3, 5, 6, 7, 9, 10, 12, 13, 17, 20, 21, 24]
If using class "Integer" instead of primitive int is not a problem you can use this, basically first do the merge and after sort them: you can do the call Arrays.sort even in the same method and call it mergeAndSort, if you want...
import java.util.Arrays;
public class Main {
public static Integer[] merge(Integer[]... arrays) {
int count = 0;
for (Integer[] array : arrays) {
count += array.length;
}
Integer[] mergedArray = (Integer[]) java.lang.reflect.Array.newInstance(arrays[0][0].getClass(), count);
int start = 0;
for (Integer[] array : arrays) {
System.arraycopy(array, 0, mergedArray, start, array.length);
start += array.length;
}
return mergedArray;
}
public static void main(String[] args) {
Integer[] array1 = {3, 5, 6, 7, 78, 100};
Integer[] array2 = {5, 6, 7, 8, 9};
Integer[] array3 = {2, 6, 7};
Integer[] merged1 = merge(array1, array2);
Arrays.sort(merged1);
Integer[] merged2 = merge(array1, array2, array3);
Arrays.sort(merged2);
printArray(merged1);
printArray(merged2);
}
public static void printArray(Integer[] x) {
System.out.println("--ToString--");
for (Integer var : x) {
System.out.println(var);
}
System.out.println("----");
}
}
public static void main(String[] args) {
int[][] arr = {{2, 3, 4}, {3, 4, 5, 2}};
System.out.println(line(arr));
}
public static int[] line(int[][] arr) {
int size = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
size++;
}
}
int[] array = new int[size];
int place = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
array[place] = arr[i][j];
place++;
}
}
return array;
}
The eror I'm getting is
----jGRASP exec: java Problem
[I#15db9742
----jGRASP: operation complete.
Every object has a toString() method, and the default method is to display the object's class name representation, then "#" followed by its hashcode. So what you're seeing is the default toString() representation of an int array. To print the data in the array, you can use
System.out.println(java.util.Arrays.toString(line(arr)));
Or you can loop through the array with a for loop like this
int [] res = line(arr);
for(int i=0;i<res.length;i++){
System.out.println(res[i]);
}
import java.util.Arrays;
public class TEst {
public static void main(String[] args) {
int[][] arr = { { 2, 3, 4 }, { 3, 4, 5, 2 } };
System.out.println(Arrays.toString(line(arr)));
}
public static int[] line(int[][] arr) {
int size = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
size++;
}
}
int[] array = new int[size];
int place = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
array[place] = arr[i][j];
place++;
}
}
return array;`enter code here`
}
}
As far as i can see it is working:
public static void main(String[] args) {
int[][] arr = {{2, 3, 4}, {3, 4, 5, 2}};
int[] i = line(arr);
Arrays.stream(i).forEach(x -> System.out.println(x + ""));
}
public static int[] line(int[][] arr) {
int size = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
size++;
}
}
int[] array = new int[size];
int place = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
array[place] = arr[i][j];
place++;
}
}
return array;
}
the only thing is when you are writing out your result you get the object reference not the array in plain text.
2
3
4
3
4
5
2
Process finished with exit code 0
I got array of ints, and I want in order to last element of this array will be shift on top N times, something like this:
int[] array = {1, 2, 3, 4, 5};
And now, last element will be shifted for example 3 times, and it should be expected result:
3, 4, 5, 1, 2
I tried like this:
int[] tab = new int[5];
tab[0] = 1;
tab[1] = 2;
tab[2] = 4;
tab[3] = 5;
tab[4] = 6;
int[] secondTab = new int[5];
int N = 3;
int j = 0;
for (int i=0; i<tab.length-1; i++){
secondTab[i] = tab[(tab.length-1)-N];
N--;
if (secondTab[i+1]==0){
secondTab[i+1] = tab[j];
}
}
It's obviously bad code, j is not getting increment at all so it works only for this example, but I'm wondering what is the best way to do it?
If you want to shift right N times, it means the element at the i-th position will be at the (i+N)%tab.lenth-th position:
for (int i = 0; i < tab.length; i++) {
secondTab[(i+N)%tab.length] = tab[i];
}
If you want to shift the elements in the original array you can try something like this :
int[] array = {1, 2, 3, 4, 5};
int nbShift = 1; // the number of desired shift
for(int i = -1; i < nbShift; i++){
int f = array[0];
for(int j = 0; j < array.length -1 ; j++){
array[j] = array[j + 1];
}
array[array.length - 1] = f;
}
public static void main(String[] args) {
final int[] test = { 1, 2, 3, 4 };
shiftNTimes(test, 2);
for (final int i : test) {
System.out.println(i);
}
}
public static void shiftNTimes(int[] array, int numShifts) {
int timesShifted = 0;
while (timesShifted < numShifts) {
final int temp = array[0];
for (int i = 0; i < (array.length - 1); i++) {
array[i] = array[i + 1];
}
array[array.length - 1] = temp;
timesShifted++;
}
}
For details
Here's the problem: Write a method called swapPairs that accepts an array of integers and swaps the elements at adjacent indexes. That is, elements 0 and 1 are swapped, elements 2 and 3 are swapped, and so on. If the array has an odd length, the final element should be left unmodified. For example, the list {10,20,30,40,50} should become {20,10,40,30,50} after a call to your method.
Write method printArray that is passed an array and will print out each element.
Use this method to print the array modified by swapPairs.
This is my code:
public static void swapPairs(int[] a){
int len=a.length;
if(len%2 ==0){
for(int i=0; i<len; i=i+2){
a[i]=a[i+1];
a[i+1]=a[i];
int[] b={a[i]+a[i+1]};
}
}
if(len%2 !=0){
for(int j=0; j<len; j=j+2){
a[j]=a[j+1];
a[j+1]=a[j];
a[len-1]=a[len-1];
int[] b={a[j]+a[j+1]+a[len-1]};
}
}
}
public static void printArray(int[] a){
System.out.println(a);
}
However, what it returns is [I#2a139a55
What you need to print is Arrays.toString(a)
Now, you are just printing the Hashcode of your Array object
First, your swap method could be simplified. Add both numbers together, and then subtract each from the sum (to get the other number). Something like,
public static void swapPairs(int[] a) {
for (int i = 0; i < a.length - 1; i += 2) {
int c = a[i] + a[i + 1];
a[i] = c - a[i];
a[i + 1] = c - a[i + 1];
}
}
Then you could use Arrays.toString(int[]) to get a String. Like,
public static void printArray(int[] a) {
System.out.println(Arrays.toString(a));
}
I tested the above like
public static void main(String[] args) {
int[] t = { 1, 2, 3, 4 };
printArray(t);
swapPairs(t);
printArray(t);
}
And I got
[1, 2, 3, 4]
[2, 1, 4, 3]
After almost breaking my computer several times, here's the actual working code:
public static void swapPairs(int[] a){
int len=a.length;
if(len%2 ==0){
for(int i=0; i<len; i=i+2){
int c=a[i]+a[i+1];
a[i]=c-a[i];
a[i+1]=c-a[i+1];
}
}
if(len%2 !=0){
for(int j=0; j<len-1; j=j+2){
int c=a[j]+a[j+1];
a[j]=c-a[j];
a[j+1]=c-a[j+1];
}
a[len-1]=a[len-1];
}
}
public static void printArray(int[] a){
int len=a.length;
for(int i=0;i<len;i++)
System.out.print(a[i]+" ");
}
public static void swapPairs(int[] arr){
int length = arr.length%2 == 0? arr.length : arr.length-1;
for(int i=0; i<length; i=i+2) {
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
// print the array
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+" ");
}
}
public static void swapPairs(int[] a){
int len = a.length - a.length % 2; // if len is odd, remove 1
for(int i = 0; i < len; i += 2) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
public static void printArray(int[] a){
System.out.println(Arrays.toString(a));
}
public static void main(String[] args) {
int[] iArr1 = {10, 20, 30, 40, 50};
int[] iArr2 = {10, 20, 30, 40, 50, 60};
swapPairs(iArr1);
swapPairs(iArr2);
printArray(iArr1); // [20, 10, 40, 30, 50]
printArray(iArr2); // [20, 10, 40, 30, 60, 50]
}
final int[] number = new int[] { 1, 2, 3, 4, 5, 6, 7 };
int temp;
for (int i = 0; i < number.length; i = i + 2) {
if (i > number.length - 2) {
break;
}
temp = number[i];
number[i] = number[i + 1];
number[i + 1] = temp;
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j]);
}
import java.util.Scanner;
public class SwapEveryPair {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];
for (int i = 0; i < arr.length; i++) {
arr[i] = scn.nextInt();
}
for (int i = 0; i < (arr.length - 1); i += 2) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
for(int i=0; i< arr.length; i++){
System.out.println(" " + arr[i]);
}
}
}``
I think this should work,
public static void swapAlternate(int[] input){
for(int i=0;i<input.length - 1; i+=2){
int temp = input[i];
input[i] = input[i+1];
input[i+1] = temp;
}
}